How to build a server in Java: Part 3 - Allowing multiple users to connect

Now we will really implement this and allow multiple users to connect to the server1
Now we will really implement this and allow multiple users to connect to the server1

Servers with multiple connections

Right now, our server allows one user to connect and then just prints out what that user has sent to the server. Now that's cool but it isn't really very useful. Wouldn't it be awesome if multiple connections would be allowed and we could actually chat? Well then, let's do it!

If you haven't already please check out Part 1 and Part 2 of this tutorial series.

So what do we need to add?

Well, in order to allow multiple connections to our server we need to add something called threads. Threads essentially are the things that allow multitasking on our computers and let us run more than one thing at a time. For example, you can listen to music while writing your essay, there is a thread running the music player and a thread running your word processor and then can perform their own functions separately. So, we can set up a thread for each person who connects to our server which will allow us to have tons of people to connect to our server. If you haven't the slightest clue what a thread is then unfortunately this tutorial might not work out so well for you, try researching threads online (there are tons of tutorials out there about them) and then come back here.

Threads

Here is some code that will show you how we will be using threads to allow multiple connections:

Socket socket = sSocket.accept();
Thread socketThread = new ThreadClass(socket);
socketThread.start();

We will run this code every time someone connects and this will essentially place their connection in it's own thread. This thread will handle everything for that one client. Unfortunately we can't just say "RUN THE SOCKET" and it will suddenly magically receive connections from the client, print them out, and send them to all the other clients. So, we essentially create our own custom thread. Here is some code that will outline how this will work:

//We need to use "implements Runnable to tell Java that this is a thread
class ClientThread implements Runnable {
    //This run method is what is executed when the thread starts
    public void run()
    {
        //Set up the PrintWriter and BufferedReader here
        while(true) {
            //Get info sent from client
            String clientInput = input.nextLine();
            //Here would would have a for loop that would send the
            //client's message to every other client connected.
        }
    }
}

Okay, now that you know a little about threads and what we're going to do with them lets redo the server code.

The New Server Code

import java.net.*;
import java.util.*;
import java.io.*;

public class Server
{
    public static void main(String[] args)
    {
        new Server();
    }
    
    public Server()
    {
        //We need a try-catch because lots of errors can be thrown
        try {
            ServerSocket sSocket = new ServerSocket(5000);
            System.out.println("Server started at: " + new Date());
            
            
            //Loop that runs server functions
            while(true) {
                //Wait for a client to connect
                Socket socket = sSocket.accept();
            
            
                
                //Create a new custom thread to handle the connection
                ClientThread cT = new ClientThread(socket);
                
                //Start the thread!
                new Thread(cT).start();
                
            }
        } catch(IOException exception) {
            System.out.println("Error: " + exception);
        }
    }
    
    //Here we create the ClientThread inner class and have it implement Runnable
    //This means that it can be used as a thread
    class ClientThread implements Runnable
    {
        Socket threadSocket;
        
        //This constructor will be passed the socket
        public ClientThread(Socket socket)
        {
            //Here we set the socket to a local variable so we can use it later
            threadSocket = socket;
        }
        
        public void run()
        {
            //All this should look familiar
            try {
                //Create the streams
                PrintWriter output = new PrintWriter(threadSocket.getOutputStream(), true);
                BufferedReader input = new BufferedReader(new InputStreamReader(threadSocket.getInputStream()));
                
                //Tell the client that he/she has connected
                output.println("You have connected at: " + new Date());
                
                while (true) {
                    //This will wait until a line of text has been sent
                    String chatInput = input.readLine();
                    System.out.println(chatInput);
                }
            } catch(IOException exception) {
                System.out.println("Error: " + exception);
            }
        }
    }
}

The Explanation

So for this new code you can see that we only have to change the server's code. You can use the client code from the last tutorial to connect to the server. The main thing now is that, each time a socket connection is accepted, that socket is passed off to a thread which runs the socket. Once that socket has been passed off to the thread the server then waits for a new socket connection.

Try it!

So now run the code for the server, then run the client code twice and try typing messages in either of them. The server will receive data from both the clients!!!!!! It works!!!!! But, it's still not really exciting. Bummer. Well not for long because in Part 4 we will be adding a user-interface to the server and make it into an actual chat server!!! So head on over to Part 4.

More by this Author


Comments 9 comments

Arwa 4 years ago

Great tutorials! Really gonna help me with my graduation project this semester. Waiting for part 4!


Dave 4 years ago

Hey, where's part 4? This was written back in October man! lol I can't be so demanding but this series was really going somewhere.


Drenguin profile image

Drenguin 4 years ago from Somewhere Author

Ah, I'm sorry. I became obsessed with HubPages for like 3 weeks and then just stopped. I will try to upload something but unfortunately I can't guarantee anything. Thanks for showing interest in this though, hopefully this will inspire me to start writing again!


Micaiah 4 years ago

Ya, I second on part 4 really wanting to get my game server up and running! Thanks for the other parts, they were great!


Anon 4 years ago

testing testing


Dave 4 years ago

Well, the good thing is you responded. I totally thought this page would be lost the annals of the Internet.

Your code helped a lot in creating the client/server part of a game I was working on, but I ignored the whole thread safety issue, which made things a little.... problematic. lol


Futamarka 3 years ago

Стоимость экскурсии 2320 рублей. К Гавриле-ямщику на блины! 16, 17 марта Ах, хороша ты, Масленица в русской глубинке! Масленица, овеянная «ямщицкой» экзотикой в столице ямщиков - городе Гаврилов Ям! Искреннее, широкое гулянье, пронизанное глубинным народным юмором. Повязав ленточку на «Дугу счастья», загадайте заветное желание, и оно обязательно сбудется!


Mylindaminka 3 years ago

3. Спонтанно-ситуационный, связанный с непредсказуемой частью процесса. Эту часть процесса невозможно предварить специальной установкой, но если его не будет, то никто не придет смотреть эту игру, равно как никому и причёскать в нее будет не интересно.


Utertelpego 3 years ago

BEIJING, Hangzhou, October 26 (Reporter Xia Yi intern Zhu Xiaoxia) In this particular Daxing Finance & ldqlouis vuitton online shopuo; hydraulic "era, the 26th, Zhejiang Vice Governor Zhu Zhejiang at the Second World Conference , said Zhejiang money in many places, but the most cash-strapped two places, one is a large number of small and micro enterprises, and the other is the need to transition innovative industries. "We hope that through financial reform can lead to the most money possible need water place. "In the afternoon, including the deputy governor of Zhejiang Province, Zhu, Alibaba Chairman Jack Ma, Zhejiang Materials Industry Group Chairman Wang Ting Ge, former assistant secretary of the U.S. Department of Commerce John Huang, who co-launched on financial innovation issues $ $ $ $ $ $ a Field brainstorming. Wenzhou, Zhejiang comprehensive reform pilot financial year and a half has gone. May 2012, the State Council Wenzhou comprehensive financial reform pilot program launched soon, 47-year-old Zhu, Zhejiang cursory from the Commission, has been appointed louis vuitton taschen based grasping finance Vice Governor, outside of louis vuit chanel en ligne ton online shop The Young Turks technical officials have high hopes, Wenzhou financial reform has been given a global breakthrough in Chinas financial reform and the many missions. Zhu said that the day of the forum, Zhejiang, financial innovation is not started from several test points, in fact, private enterprises in Zhejiang has been accompanied by financial innovation. He said that Zhejiang has changed a great feature, both past and present, are closely linked to the actual Zhejiang Province, "the biggest are actually two, one is the master of private capital, a large number of small and micro enterprises are . "He believes that now run, Wenzhou financial reform is very strong, has played a certain role. In the progress of financial reform, first, expanding the types of collateral, the second is already put on the small micro-enterprise credit system construction, as the focus of reform. However, Zhejiangxinhu bearish Lin Junbo Group Co., Ltd. Zhejiang several financial reform pilot sites. She believes that financial policies are being above the interest rate market and so there will be no breakthrough, financial reform will be a modicum of success in Zhejiang, but it is difficult as there are big. For pessimism from the company, Zhu said that the financial reform is the start of Zhejiang economic transformation and upgrading, innovation and development also needs financial modernization, according to modern finance financial idea to regulate development. (End)

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working