Server recieves message after client disconnects

In my project there is a server that sits for clients and serves them.

The server—- Main

    ss = new ServerSocket(12345);
    System.out.println("Server started..");
    while(true)
    {
        System.out.println("Waiting For clients...");
        Socket client = ss.accept();
        System.out.println("Got client...");
        Thread t = new Thread(new Handler(client));
        t.start();
        //exe.execute(new Handler(client));

    }

This is in the main method, the server creates an infinite loop (thread) that will accept incoming connections. Once a connection has been received the server will create a new Handler object that takes the client who has connected as an argument.

The Handler class

    public class Handler implements Runnable {

    Socket client;

    public Handler(Socket client) {
        // TODO Auto-generated method stub
        this.client = client;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //streams 
        try {
            OutputStream out = client.getOutputStream();
            PrintWriter writer = new PrintWriter(out);

            InputStream in = client.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String s = null;

            while((s=reader.readLine())!=null)
            {

                //will switch on string or convert to json object
                System.out.println("Recieved: " + s);
            }
            writer.close();
            reader.close();
            client.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

In this class the main objective is to handle the clients request. So the constructor initializes the socket object to it’s owning instance.

in the run method the objects are instantiated, and then there is an infinite loop which is suppose to print any incoming messages from clients.

The loop will break when the client disconnects, and this is where the close() method is called, to gracefully close and release resources. With this the thread ends.

The Client – (Android)

    public class MainActivity extends AppCompatActivity {

    final String ip = "192.168.0.18";
    final int port = 12345;
    Socket client;
    OutputStream out;
    PrintWriter writer;

    InputStream in;
    BufferedReader reader;
    final String TAG = "Debug: ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ConnectToServer().execute();
        new SendToServer().execute();


    }

    class ConnectToServer extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params)
        {
            try {
                client = new Socket(ip,port);
                //Log.d(TAG, "doInBackground: connected to server");
                //set streams
                out = client.getOutputStream();
                writer = new PrintWriter(out);

                in = client.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));

                Log.d(TAG, "doInBackground: Sent");



            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    class SendToServer extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params) {
            writer.write("lol");
            writer.flush();
            return null;
        }
    }

}

Last time I played with Android Studio was a year ago or so, and I am very positive that network/IO operations were possible to run on the main thread. But the golden rule implies to not block the main thread, and there are some blocking methods.

I chose to use the AsyncTask interface since it encapsulates the lower level Thread class (Easier to use/ understand the life cycle for me).

The ConnectToServer class successfully connects to the server, but once the SendToServerclass is called, the server doesn’t receive the message.

Once I disconnect the client (terminate the app) the server then prints out the messages.

Why is the server receiving the messages after the client disconnects?

Answer

You’re reading lines but you aren’t writing lines. Add a line terminator to the message being sent, or use println() instead of write().

Leave a Reply

Your email address will not be published. Required fields are marked *