在 Java Eclipse 中使用客户端服务器多线程编程添加两个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28398001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 22:23:50  来源:igfitidea点击:

Adding two numbers using Client Server Multi threading programming in Java Eclipse

javaeclipsemultithreadingsockets

提问by Murali M

The below client server program is not giving me any out put. I want to add two numbers. I am new Java programming. After entering second number , there is blank space below. What's wrong am doing below. Please help me solve this issue. Thanks.

下面的客户端服务器程序没有给我任何输出。我想添加两个数字。我是新的 Java 编程。输入第二个数字后,下方有空格。下面有什么问题。请帮我解决这个问题。谢谢。

Client.Java

客户端.Java

        package Client.java;

     import java.net.*;
    import java.io.*;
    import java.util.Scanner;

 public class GreetingClient
{
   public static void main(String [] args)
 {
  Scanner userInput = new Scanner(System.in);

  System.out.println("Enter Server Address: ");
  String serverName;
  serverName = userInput.next(); 

  System.out.println("Enter Port Number: ");
  String port;
  port = userInput.next(); 


  try
  {
     System.out.println("Connecting to " + serverName
                         + " on port " + port);
     Socket client = new Socket(serverName, Integer.parseInt(port));
     System.out.println("Just connected to "
                  + client.getRemoteSocketAddress());
     OutputStream outToServer = client.getOutputStream();
     DataOutputStream out =
                   new DataOutputStream(outToServer);

     System.out.println("Enter a first number: ");

      //userInput.nextInt();
      Integer x= userInput.nextInt();
      System.out.println("Enter a second number: ");
    //  userInput.nextInt();
      Integer y= userInput.nextInt();


    //  System.out.println("hello");


      out.writeInt(x);
      out.writeInt(y);

     InputStream inFromServer = client.getInputStream();
     DataInputStream in =
                    new DataInputStream(inFromServer);
     System.out.println("Server responds: " +in.readInt());
     client.close();
  }catch(IOException e)
  {
     e.printStackTrace();
  }

} }

} }

Server.Java

服务器.Java

   `        package Client.java;

  import java.net.*;
  import java.io.*;
  import java.util.Scanner;

   public class GreetingServer extends Thread
  {
   private ServerSocket serverSocket;

    public GreetingServer(int port) throws IOException
   {
    serverSocket = new ServerSocket(port);
     serverSocket.setSoTimeout(100000);
    }

    public void run()
    {
    while(true)
      {
     try
     {
        System.out.println("Waiting for client on port " +
        serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to "
              + server.getRemoteSocketAddress());
        DataInputStream in =
              new DataInputStream(server.getInputStream());





   Integer x=in.readInt();
   System.out.println("Hellox");
   Integer y=in.readInt();
    System.out.println("Helloy");

       // System.out.println(x);
        //System.out.println(y);


        Integer sum = ( x + y );
        DataOutputStream out =
             new DataOutputStream(server.getOutputStream());

    //  System.out.println(sum);
        out.write(sum);




        server.close();
     }catch(SocketTimeoutException s)
     {
        System.out.println("Socket timed out!");
        break;
     }catch(IOException e)
     {
        e.printStackTrace();
        break;
     }
    }
   }
     public static void main(String [] args)
       {

  Scanner userInput = new Scanner(System.in);
  System.out.println("Please specify a port number (1~65535): ");
  String port;
  port = userInput.next(); 

  try
  {
     Thread t = new GreetingServer(Integer.parseInt(port));
     t.start();
  }catch(IOException e)
  {
     e.printStackTrace();
     }
    }
      }`

回答by anishpatel

In your server program, replace

在您的服务器程序中,替换

out.write(sum);

with

out.writeInt(sum);

If you notice, you are correctly using out.writeIntin your client program.

如果您注意到,您就out.writeInt在您的客户端程序中正确使用。

回答by CESAR MURILO DA SILVA JUNIOR

My solution, from Brazil:

我的解决方案,来自巴西:

public class SocketSomaClient {
     /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int porta = 5050;
        String ip = "localhost";
        Scanner userInput = new Scanner(System.in);


        try{
            Socket socket = new Socket(ip, porta);

            DataOutputStream output = new DataOutputStream(socket.getOutputStream());

            System.out.println("Entre com o primeiro número: ");
            int x= userInput.nextInt();

            System.out.println("Entre com o segundo número: ");
            int y= userInput.nextInt();

            output.writeInt(x);
            output.writeInt(y);

            DataInputStream  input = new DataInputStream(socket.getInputStream());

            int soma = input.readInt();
            System.out.println("A soma dos dois números é: "+ soma);

        }catch(IOException ex){
            System.err.println(ex.getMessage());
        }
    }
}

public class SocketSomaServer {
    public static void main(String[] args) {

        try{

                ServerSocket serverSocket = new ServerSocket(5050);

                while(true){
                    // aguarda conex?es
                    Socket socket = serverSocket.accept();
                    try{
                    // recupera os dados
                    DataInputStream  input = 
                            new DataInputStream(socket.getInputStream());

                    Integer x = input.readInt();
                    Integer y = input.readInt();

                    Integer sum = ( x + y );
                    DataOutputStream out =
                         new DataOutputStream(socket.getOutputStream());
                    out.writeInt(sum);

                 }catch(SocketTimeoutException s)
                 {
                    System.out.println("Socket timed out!");
                    break;
                 }catch(IOException e)
                 {
                    e.printStackTrace();
                    break;
                 }
                }

        }catch(Exception ex){
            System.err.println(ex.getMessage());
        }

    }
}

回答by Abhinav

It depends on the server what is being written to the output stream. As you write without providing the data type. You need to retrieve in similar fashion.

这取决于服务器写入输出流的内容。在您编写时不提供数据类型。您需要以类似的方式检索。

 Integer sum = ( x + y );
    DataOutputStream out =
         new DataOutputStream(server.getOutputStream());

//  System.out.println(sum);
    out.write(sum);

while reading in the client just use read as below.

在客户端阅读时只需使用 read ,如下所示。

InputStream inFromServer = client.getInputStream();
         DataInputStream in =
                        new DataInputStream(inFromServer);
         System.out.println("Server responds: " +in.read());

Do not specify int type as show above.

不要指定 int 类型,如上所示。

Please find the complete code below.

请在下面找到完整的代码。

Client Code

客户代码

    package Client.java;

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class GreetingClient {
    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);

        System.out.println("Enter Server Address: ");
        String serverName;
        serverName = userInput.next();

        System.out.println("Enter Port Number: ");
        String port;
        port = userInput.next();

        try {
            System.out.println("Connecting to " + serverName + " on port " + port);
            Socket client = new Socket(serverName, Integer.parseInt(port));
            System.out.println("Just connected to " + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);

            System.out.println("Enter a first number: ");

//userInput.nextInt();
            Integer x = userInput.nextInt();
            System.out.println("Enter a second number: ");
//  userInput.nextInt();
            Integer y = userInput.nextInt();

//  System.out.println("hello");

            out.writeInt(x);
            out.writeInt(y);

            DataOutputStream os = new DataOutputStream(client.getOutputStream());
            BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));

            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("Server responds: " + in.read());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server Code

服务器代码

package Client.java;

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class GreetingServer extends Thread {
    private ServerSocket serverSocket;

    public GreetingServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(100000);
    }

    public void run() {
        while (true) {
            try {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("Just connected to " + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());

                Integer x = in.readInt();
                System.out.println("Hellox");
                Integer y = in.readInt();
                System.out.println("Helloy");

                // System.out.println(x);
                // System.out.println(y);

                Integer sum = (x + y);
                DataOutputStream out = new DataOutputStream(server.getOutputStream());

                // System.out.println(sum);
                out.write(sum);

                server.close();
            } catch (SocketTimeoutException s) {
                System.out.println("Socket timed out!");
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }

    public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);
        System.out.println("Please specify a port number (1~65535): ");
        String port;
        port = userInput.next();

        try {
            Thread t = new GreetingServer(Integer.parseInt(port));
            t.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}