angel_30
angel_30

Reputation: 1

Persistent client-server socket connection in Java

I'm trying to establish a two-way communication in Java. For that I created a simple client-server program (I'm not even sure if that's the right approach because both of them are considered client!). My requirement is that once the two program are connected, they should maintain the connection, and be able to send messages once in a while. However, currently my socket terminates once it had sent the data (client's main method has been executed).

How can I maintain the connection, so to make it persistent?

P.S: Is there any ways to make it work in an asynchronous way that might be more suitable for my requirements (I don't want the server always looping inside a while)?

Client:

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient2 {
    String serverHostname = new String("127.0.0.1");
    BufferedReader stdIn;
    Socket echoSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    public void open(){
        System.out.println("Attemping to connect to host " + serverHostname
                + " on port 9999.");
        try {
            echoSocket = new Socket(serverHostname, 9999);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + serverHostname);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for " + "the connection to: "
                    + serverHostname);
        }
    }

    public void send(String s){
        out.println(s);
    }

    public String receive(){
        String result = "";
        try {
            result = in.readLine();
            System.out.println("client received: "+result);
            if(result==null)
                return "0";
        } catch (IOException e) {
        }
        return result;
    }


    public static void main(String[] args) {
        EchoClient2 ec = new EchoClient2();
        ec.open();
        ec.send("1");
        ec.receive();
    }
}

Server:

package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer extends Thread {
    protected Socket clientSocket;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("Connection Socket Created");
            try {
                while (true) {
                    System.out.println("Waiting for Connection");
                    new EchoServer(serverSocket.accept());
                }
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port: 9999.");
            System.exit(1);
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Could not close port: 9999.");
                System.exit(1);
            }
        }
    }

    private EchoServer(Socket clientSoc) {
        clientSocket = clientSoc;
        start();
    }

    public void run() {
        System.out.println("New Communication Thread Started");

        try {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
                    true);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    clientSocket.getInputStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                System.out.println("Server received: " + inputLine);
                out.println(inputLine);

                if (inputLine.equals("Bye."))
                    break;
            }

//          out.close();
//          in.close();
//          clientSocket.close();
        } catch (IOException e) {
            System.err.println("Problem with Communication Server");
            System.exit(1);
        }
    }
}

Upvotes: 2

Views: 3852

Answers (1)

Aniket
Aniket

Reputation: 401

First of all sorry for the late answer. I am also stuck in this java socket programming. I also want to open a socket and keep it open for communication between client and server. And after searching and reading many books and articles I found the easiest solution. You can use android life cycles for your work in

Open the socket on onStart method

  protected void onStart() {
        super.onStart();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client = new Socket(ip,Integer.valueOf(port) );
                    client.setKeepAlive(true);

                   dataInputStream = new DataInputStream(client.getInputStream());
                  //  readdata=readdata+" "+dataInputStream.readUTF();

                    readdata=dataInputStream.readUTF();
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

and close the socket on onStop method

 protected void onStop() {
        super.onStop();
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Upvotes: 1

Related Questions