Java初学者(Client-Server):将多个整数发送到套接字

时间:2016-01-09 14:44:06

标签: java sockets integer client-server

我有一个非常简单的赋值,我应该将2个整数发送到套接字,它将它们的总和发送回“客户端”。

这是我的客户:

int a,b,sum;
    try
    {
        Socket Server_info = new Socket ("localhost", 15000);
        BufferedReader FromServer = new BufferedReader (new InputStreamReader(Server_info.getInputStream()));
        DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
        while (true)
        {
            System.out.println("Type in '0' at any point to quit");
            System.out.println("Please input a number");
            a = User_in.nextInt();
            ToServer.writeInt(a);
            System.out.println("Please input a second number");
            b = User_in.nextInt();
            ToServer.writeInt(b);
            sum = FromServer.read();
            System.out.println("the sum of "  +a+ " and " +b+ " is: " +sum );
            if (a==0 || b==0)
                break;
        }

这是我的套接字处理程序:

int num1=0 ,num2=0, sum;
    try
    {
        BufferedReader InFromClient = new BufferedReader (new InputStreamReader(soc_1.getInputStream()));
        DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
        while (true)
        {
            num1 = InFromClient.read();
            num2 = InFromClient.read();
            sum = num1 + num2 ;
            OutToClient.writeInt(sum);
        }
    }
    catch (Exception E){}

在运行客户端后的第一个Integer输入后,我得到了这个:

  

在任何时候输入'0'退出

     

请输入一个数字

     

5

     

通过对等方重置连接:套接字写入错误

我认为问题出现在套接字接收端,我一定是做错了。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您可以使用DataInputStream和DataOupStream对象,但我发现在服务器端和客户端都使用一对Scanner和PrintWriter对象比较简单。所以这是我对问题的解决方案的实现:

服务器端

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

public class TCPEchoServer {

    private static ServerSocket serverSocket;
    private static final int PORT = 1234;

    public static void main(String[] args)
    {
        System.out.println("Opening port...\n");
        try {
            serverSocket = new ServerSocket(PORT);
        }
        catch (IOException ioex){
            System.out.println("Unable to attach to port!");
            System.exit(1);
        }
          handleClient();

  }

    private static void handleClient()
    {
        Socket link = null; //Step 2
        try {
            link = serverSocket.accept(); //Step 2
            //Step 3
            Scanner input = new Scanner(link.getInputStream());
            PrintWriter output = new PrintWriter(link.getOutputStream(), true);
            int firstInt = input.nextInt();
            int secondInt = input.nextInt();
            int answer;

            while (firstInt != 0 || secondInt != 0)
            {
                answer = firstInt + secondInt;
                output.println(answer); //Server returns the sum here 4
                firstInt = input.nextInt();
                secondInt = input.nextInt();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                System.out.println("Closing connection...");
                link.close();
            }
            catch (IOException ie)
            {
                System.out.println("Unable to close connection");
                System.exit(1);
            }
        }
    }
}

客户端

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


public class TCPEchoClient {

    private static InetAddress host;
    private static final int PORT = 1234;

    public static void main(String[] args) {
        try {
            host = InetAddress.getLocalHost();
        } catch (UnknownHostException uhEx) {
            System.out.println("Host ID not found!");
            System.exit(1);
        }
        accessServer();
    }

    private static void accessServer() {
        Socket link = null;    //Step 1
        try {
            link = new Socket(host, PORT); //Step 1
            //Step 2
            Scanner input = new Scanner(link.getInputStream());
            PrintWriter output = new PrintWriter(link.getOutputStream(), true);

            //Set up stream for keyboard entry
            Scanner userEntry = new Scanner(System.in);

            int firstInt, secondInt, answer;
            do {
                System.out.print("Please input the first number: ");
                firstInt = userEntry.nextInt();
                System.out.print("Please input the second number: ");
                secondInt = userEntry.nextInt();

                //send the numbers
                output.println(firstInt);
                output.println(secondInt);
                answer = input.nextInt(); //getting the answer from the server
                System.out.println("\nSERVER> " + answer);
            } while (firstInt != 0 || secondInt != 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (NoSuchElementException ne){   //This exception may be raised when the server closes connection
            System.out.println("Connection closed");
        }
        finally {
            try {
                System.out.println("\n* Closing connection… *");
                link.close(); //Step 4.
            } catch (IOException ioEx) {
                System.out.println("Unable to disconnect!");
                System.exit(1);
            }
        }
    }
}

答案 1 :(得分:0)

问题是你混合了流和读者。 为了成功地将整数从客户端传递到服务器,例如使用Data [Input / Output] Stream,您应该使用:

    // Server side
    final DataInputStream InFromClient = new DataInputStream(soc_1.getInputStream());
    final DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
    // than use OutToClient.writeInt() and InFromClient.readInt()

    // Client side
    final DataInputStream FromServer = new DataInputStream(Server_info.getInputStream());
    final DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
    // than use ToServer.writeInt() and FromServer.readInt()

如果您说从客户端向服务器发送一个int(在本例中使用DataOutputStream.writeInt),使用相应的解码逻辑(在我们的示例中为DataInputStream.readInt)读取数据非常重要。