Shubham Singh
Shubham Singh

Reputation: 211

Sample code to make a persistent TCP connection in java

I want to create a sample TCP client-server pair. The client will take input string from console and send it to server, server will print the request string and respond back with some string. I don't want close the connection once a transaction is done, using the same connection I want to keep on sending request and getting response from server.

I have written the following client-server code , first transaction happens correctly but when I try to send second request, nothing is received by server and client hangs. I tried to google for solution but could not find anything helpful. Please help.

Client Code

public class Client {

    public static void main( String[] args ) throws UnknownHostException, IOException {
         Socket clientSocket = new Socket( "localhost", 81 );
         DataOutputStream out = new DataOutputStream( clientSocket.getOutputStream() );
         BufferedReader in =
            new BufferedReader( new InputStreamReader( clientSocket.getInputStream() ) );
         System.out.println( "connected to server" );

         while ( true ) {
             System.out.println( "enter data to send" );
             Scanner sc = new Scanner( System.in );
             String msg = sc.nextLine();
             out.writeBytes( msg + "\n" );
             System.out.println( "response from server : "+in.readLine() );

        }

    }
}

Server Code

public class Server {

    public static void main(String args[]) throws IOException{
        ServerSocket ss = new ServerSocket(81);
        System.out.println( "server started" );
        while(true){
            System.out.println( "waiting for client" );
            Socket s = ss.accept();
            System.out.println( "connected to client" );
            BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream() ) );
            DataOutputStream out = new DataOutputStream( s.getOutputStream() );
            out.flush();
            System.out.println( "recieved: "+ in.readLine()  );
            out.writeBytes( "200\n" );
        }
    }
}

Upvotes: 0

Views: 4203

Answers (2)

Duško Mirković
Duško Mirković

Reputation: 252

As Zachary has said his solution would work for single client only, for multiple clients you will need to make a new thread for each client like this:

public class Server {

    private ServerSocket server;

    public Server(int port) {
        server = new ServerSocket(port);
    }

    public void listenForConnections() {
        while (true) {
            Client client = new Client(server.accept());
            new Thread(client).start();
        }
    }

}

public class Client implements Runnable {

    private Socket socket;

    public Client(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        while (true) {
            // Do something
        }
    }

}

Upvotes: 1

Zachary
Zachary

Reputation: 1703

When your server begins, it creates a server socket bound on port 81 and enters an infinite loop. Within this loop, you start in an "accepting" state, where you listen for a connection to be made and accept it. Upon accept, you wait for a line of input from the client, print it to System.out, and respond with a "200" response. The problem you have is that after you have responded, the loop 'resets', and you start listening for a new connection.

The simplest solution is to continuously check for incoming data in your server.

public class Server {

    public static void main(String args[]) throws IOException{
        ServerSocket ss = new ServerSocket(81);
        while(true){
            Socket s = ss.accept();
            BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream() ) );
            DataOutputStream out = new DataOutputStream( s.getOutputStream() );
            while (true) {
                System.out.println( "recieved: "+ in.readLine()  );
                out.writeBytes( "200\n" );
                out.flush();
            }
        }
    }
}

While this would work for a single client, this would prevent you from establishing new connections while you are listening for data. You may want to create a new thread for each connection to handle reading/writing for each distinct socket connections.

Upvotes: 4

Related Questions