简体   繁体   English

Java初学者(客户端-服务器):将多个整数发送到套接字

[英]Java beginner (Client-Server) : Sending multiple Integers to a socket

i have a very simple assignment in which i am supposed to send 2 integers into a socket, which sends their sum back to the "client". 我有一个非常简单的分配,其中我应该向套接字发送2个整数,该整数将它们的总和发送回“客户端”。

this is my client: 这是我的客户:

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;
        }

this is my socket handler: 这是我的套接字处理程序:

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){}

After the first Integer input upon running the client i get this: 在运行客户端的第一个Integer输入后,我得到以下信息:

Type in '0' at any point to quit 随时输入“ 0”退出

Please input a number 请输入一个数字

5 5

Connection reset by peer: socket write error 对等方重置连接:套接字写入错误

i think the problem lays at the socket receiving side, i must be doing something wrong. 我认为问题出在插座接收端,我一定做错了。 any suggestions? 有什么建议么?

You can use DataInputStream and DataOupStream objects but I find it simpler to user a pair of Scanner and PrintWriter objects both at the server side and client side. 您可以使用DataInputStream和DataOupStream对象,但我发现在服务器端和客户端都使用一对Scanner和PrintWriter对象更为简单。 So here is my implementation of the solution to the problem: 所以这是我对问题的解决方案的实现:

The Server Side 服务器端

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);
            }
        }
    }
}

The Client Side 客户端

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);
            }
        }
    }
}

The problem is that you mix streams and readers. 问题是您混合了流和阅读器。 In order to successfully pass integers from client to server, for example with Data[Input/Output]Stream you should use: 为了成功地将整数从客户端传递到服务器,例如,使用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()

If you let's say send an int from client to server (in this case using DataOutputStream.writeInt), it is very important to read the data with the corresponding decoding logic (in our case DataInputStream.readInt). 如果您说从客户端到服务器发送一个int(在这种情况下,使用DataOutputStream.writeInt),则使用相应的解码逻辑(在我们的示例中是DataInputStream.readInt)读取数据非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM