简体   繁体   中英

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".

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:

Type in '0' at any point to quit

Please input a number

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. 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:

    // 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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