Search code examples
javasocketstcp

TCP Server only receives one message


I am trying to create a simple TCP server and client. I want the client to be able to send multiple messages by only opening the socket once. I have looked at similar questions here, here, and here but they haven't been much use.

My code is a follows:

SampleServerTCP.java

public class SampleServerTCP {
    private static final int DEFAULT_PORT_NUMBER = 39277;

    public static void main(String[] args) throws IOException {
        ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);

        System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
        while (true){
            Socket connectionSocket = defaultSocket.accept();
            BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
            String msg = fromClient.readLine();
            System.out.println("Recieved: " + msg);
        }
    }
}

TCPClientTest.java

public class TCPClientTest {

    public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException{
        Socket clientSocket = new Socket("localhost", 39277); 
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        int c = 0;
        while(c<10){
            outToServer.writeBytes(c + "\n");
            outToServer.flush();
            c++;
            Thread.sleep(500);
        }
        clientSocket.close();
    }
}

The only output I get is:

Listening on port: 39277
Recieved: 0

Where am I going wrong?


Solution

  • Your problem lies here:

    ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
    
        System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
        while (true){
            Socket connectionSocket = defaultSocket.accept();
            BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
            String msg = fromClient.readLine();
            System.out.println("Recieved: " + msg);
        }
    

    You are opening the socket, reading only one line and then you are waiting for the next socket.

    Instead you should do Socket connectionSocket = defaultSocket.accept(); outside your while loop, and read from this socket in your loop, like this:

    System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
    Socket connectionSocket = defaultSocket.accept();
    BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
    String msg = "";
    while ((msg = fromClient.readLine()) != null){    
        System.out.println("Recieved: " + msg);
    }