Sunday, January 6, 2013

Multi-Threaded Socket Programming in Java (Part II- Client)

As you saw in first part of Multi-Threader Socket Programming, we handled everything from the server's point of view. There are not so much thing going on at the client's side, and technically speaking you should bear in mind that client will not even know how the server processes its request. So the client part's code is not really dependent toward the context of threading obviously.
        
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            socket = new Socket("Amir", 8081);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: Amir.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: Amir.");
            System.exit(1);
        }

As you can see, we initiated the socket with the Server Socket's name and port. The PrintWriter is getting the output stream of the socket so that we can later write on it and we also initialized an BufferedReader object to receive the stream of server's response.
        
        String serverMessage;
        while ((serverMessage = in.readLine()) != null) {
            System.out.println("Server: " + serverMessage);
            if (serverMessage.contains("MESSAGE RECEIVED"))
                break;
        }  

As you can see, listening for server's response and if the Server's response contains the String literal "MESSAGE RECEIVED", the loop is broken. This part is inside my very own protocol, and you can have whatever you would like to have there. Finally, you just have to remember to close the streams and sockets in order to avoid any resource leaks:

        out.close();
        in.close();
        socket.close();

So we are done. I tried to come up with something very easy and therefore you do not get lost in there. However, if anyone is interested in having a whole sort of real application up and running, take a look at the Source repository here: https://github.com/fidelio-coder/MultiThreadServer 

No comments:

Post a Comment