Android and Java sockets – simple messenger

Hello all, as you requested in the previous TCP server-client tutorials, I made a new tutorial on how to create multiple client connections to a single server.

I posted the projects on GitHub here for you so I will post here only the main classes and functionality that I consider important to walk through. You will find there the Android client and the Java server, both should be ready to run.

OK so I started using the old project and changed it a bit to support multiple client connections.

Part 1 – The Client (User)

I will first explain what I added new on the Android side. I added a new Preference Activity class where the user can set its username for now(you can add there other stuff).

I linked the saved username preference value to the client connection so that the client will send each time the correct username and not a hard coded one.

// send login name
sendMessage(Constants.LOGIN_NAME + PreferencesManager.getInstance().getUserName());

I also check if the user set his username whenever he presses the “Connect” button and if he doesn’t, I display an error message inside a Toast.

String username = PreferencesManager.getInstance().getUserName();

// check if we have the username saved in the preferences, if not, notify the user to write one down
if (username != null) {
    // connect to the server
    new ConnectTask().execute("");
} else {
    Toast.makeText(this, "Please go to preferences and set a username first!", Toast.LENGTH_LONG).show();

That’s all for the client.

Part 2 – The server side

OK so to make the old server accept multiple connections, I had to make a loop and listen to new connections instead of trying to get only the first connection that gets into way like in the simple sample.

Before starting with that, I created a new model called User, the user class contains simple data of a real user like username, user id and the message he is trying to send.

Also I made a new UserManager class that manages a single client connection at a time. The UserManager class is basically what was before the TcpServer but id doesn’t contain the server socket as it handles only a client socket.

UserManager extends Thread to run a new loop on a secondary thread that listens to incoming messages from the client and also has the ability to send messages to that client.

On the TcpServer class I changed the runServer() method and make it like this:

private void runServer() {
        running = true;

        try {
            //create a server socket. A server socket waits for requests to come in over the network.
            serverSocket = new ServerSocket(SERVERPORT);

            while (running) {
                // create a loop and get all the incoming connections and create users with them

                System.out.println("S: Waiting for a client ...");

                //create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
                Socket client = serverSocket.accept();

                UserManager userManager = new UserManager(client, this);
                // add the new user to the stack of users

                // start reading messages from the client

                System.out.println("S: New client connected ...");

        } catch (Exception e) {
            System.out.println("S: Error");

That way the server will continuously search for new client connections and every time it catches one, creates a new UserManager and passes out the client socket to the manager in order to start the secondary thread where the messages are awaited.

Please note that the sample code can be enhanced and is just as an example.

At the moment the server can send only broadcast messages. As an exercise you can try and enhance it and create your version that can send messages only to a certain user or so.

I hope the code is documented enough, if not, please post your problem here and I will try to help you.


Q: I started my client and server but I can’t see any messages, why?
1. Please take a look at your logs, both on Android and Java and if you got some errors, your best friend is google and stackoverflow, if that doesn’t solve the problem then please post a comment here with the logs and the steps to reproduce the issue.
2. If no logs appear, please make sure you have the client and server devices in the same network and the firewall doesn’t block any of them.

Thank you ! :)

Exit mobile version