How can I keep TCP connection alive with Java?

14,031

The simplest thing would be to put a loop in the client code. Something like this:

   while ((modifiedSentence = inFromServer.readLine()) != null) {
       System.out.println("FROM SERVER: " + modifiedSentence);
       sentence = inFromUser.readLine();
       outToServer.writeBytes(sentence + '\n');
   }

The readLine() method blocks while waiting for messages from the server, so the client will not exit.

See bellow a simple tutorial on how to write a socket server and client:

http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Share:
14,031
Koray Tugay
Author by

Koray Tugay

Crappy software developer who does not like self-promoting profiles.

Updated on July 16, 2022

Comments

  • Koray Tugay
    Koray Tugay almost 2 years

    What I want to do is:

    1) Create a TCP socket listening to a particular port number in my local machine. ( Server )

    2) Create another TCP socket that will connect to the first TCP socket I have created.( Client )

    3) Send some data to the Server via Client.

    4) Receive data by Client from the Server.

    5) Do NOT close the connection.. Wait for a little while..

    6) Receive more data from the Server.

    Here is my code:

    public class MyTCPServer {
    
        public static void main(String argv[]) throws Exception {
            String clientSentence;
            String capitalizedSentence;
            ServerSocket welcomeSocket = new ServerSocket(6789);
            while (true) {
                Socket connectionSocket = welcomeSocket.accept();
                BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                clientSentence = inFromClient.readLine();
                System.out.println("Received: " + clientSentence);
                capitalizedSentence = clientSentence.toUpperCase() + '\n';
                outToClient.writeBytes(capitalizedSentence);
                outToClient.writeBytes(String.valueOf(System.currentTimeMillis()));
                Thread.sleep(1000);
                outToClient.writeBytes(String.valueOf(System.currentTimeMillis()));
            }
        }
    
    }
    

    So this TCP socket listens to port 6789. Please notice that it sends back the received String from the Client, uppercases it and returns it back. And then the Server sends the currentTimeMillis, waits for 1000 milliseconds, and sends the timeMillis again.

    Here is my Client:

    public class MyTCPClient {
    
        public static void main(String[] args) throws Exception {
            String sentence;
            String modifiedSentence;
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
            Socket clientSocket = new Socket("localhost", 6789);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            sentence = inFromUser.readLine();
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
            System.out.println("FROM SERVER: " + modifiedSentence);
        }
    
    }  
    

    However when I test my code I get:

    Received: asdf
    Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
        at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
        at MyTCPServer.main(MyTCPServer.java:28)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    

    How can I keep the connection alive in the Client side? Also I would like to be able to send more text from the Client as well.