ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on June 16, 2012
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.


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);

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.util.*;

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();
            } 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.


    0 of 8192 characters used
    Post Comment

    • profile image


      4 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)

    • profile image


      5 years ago

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

    • profile image


      5 years ago

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

    • profile image


      6 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

    • profile image


      6 years ago

      testing testing

    • profile image


      6 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!

    • Drenguin profile imageAUTHOR


      6 years ago from Somewhere

      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!

    • profile image


      6 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.

    • profile image


      6 years ago

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


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)