ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to build a server in Java: Part 4 - A user interface

Updated on June 18, 2012

The beautiful UI

User Interface!

Okay, so we have a server running, it can accept connections from multiple clients, and we can connect to it from anywhere on the internet. However, this server doesn't look very nice. In this tutorial we are going to add a (very simple) user interface to our program using the "swing" GUI (Graphical User Interface) toolkit. Okay, let's jump right in.

Swing

Swing is part of the javax package and it is THE way to create a user interface in java. You don't have to download swing or anything, it is already included when you download java. To get swing you just need to import it by doing this:

import javax.swing.*;

To create our user interface (UI) we are going to be using JFrames, JTextAreas, and JTextFields. These are all just UI elements that we can add to our program. Now, this tutorial is not about how to create user interfaces, it is about how to add some UI to our server and our client. I will not be going into detail about how to use Swing. Hopefully you already know some Swing and can follow along!

The Code

Okay, so here is the code for the new, update server with the UI:

import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;

public class Server extends JFrame
{
    //A JTextArea to hold the information received from clients
    JTextArea chatBox = new JTextArea();
    
    public static void main(String[] args)
    {
        new Server();
    }
    
    public Server()
    {
        //We need to set up a layout for our window
        setLayout(new BorderLayout());
        //Only display text, do not allow editing
        chatBox.setEditable(false);
        //Add our chatbox in the center with scrolling abilities
        add(new JScrollPane(chatBox), BorderLayout.CENTER);
        
        setTitle("Chat Server");
        setSize(550,400);
        //If the user closes then exit out
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Show the frame
        setVisible(true);
        
        //We need a try-catch because lots of errors can be thrown
        try {
            ServerSocket sSocket = new ServerSocket(5000);
            chatBox.append("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());
                chatBox.append("Client connected\n");
                
                while (true) {
                    //This will wait until a line of text has been sent
                    String chatInput = input.readLine();
                    //Add the chat to the text box
                    chatBox.append(chatInput+"\n");
                    System.out.println(chatInput);
                }
            } catch(IOException exception) {
                System.out.println("Error: " + exception);
            }
        }
    }
}

The main changes that we have made are that we added the user interface and now, instead of doing System.out.println(), we just append the information we have to the JTextArea. The comments in the code are probably the best way to understand what is going on. Leave a comment if you have no clue what I did.

Now, try running the code and see what happens!

Client UI

Now we also need our client to get a user-interface. Again here is the code and make sure to read through the comments to see what is going on.

import java.io.*;
import java.net.*;
//We no longer need a scanner to get input!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Client extends JFrame
{
    JTextField inputField = new JTextField();
    JTextArea chatBox = new JTextArea();
    
    PrintWriter output;
    BufferedReader input;
    
    public static void main(String[] args)
    {
        new Client();
    }
    
    public Client()
    {
        //Create a panel with the UI for getting input from user
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout());
        p.add(new JLabel("Type here:"), BorderLayout.WEST);
        p.add(inputField, BorderLayout.CENTER);
        
        setLayout(new BorderLayout());
        //Add the chatBox and the panel for getting user input
        add(new JScrollPane(chatBox), BorderLayout.CENTER);
        add(p, BorderLayout.SOUTH);
        
        //Add an action listener on the text field 
        //so we can get what the user is typing
        inputField.addActionListener(new TextFieldListener());
        
        //Housekeeping stuff
        setTitle("Chat Client");
        setSize(550,550);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        
        try {
            Socket socket = new Socket("localhost",5000);
            output = new PrintWriter(socket.getOutputStream(), true);
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
            //This will wait for the server to send the string to the client saying a connection
            //has been made.
            String inputString = input.readLine();
            chatBox.append(inputString+"\n");
        } catch (IOException exception) {
            System.out.println("Error: " + exception);
        }
    }
    
    //This class handles the text field
    class TextFieldListener implements ActionListener
    {
        //This method will be called when the user hits enter
        public void actionPerformed(ActionEvent e) {
            try {
                String userInput = inputField.getText();
                output.println(userInput);
                chatBox.append(userInput+"\n");
                inputField.setText("");
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    }
}

Done!

And there you go! There is a server and a client with some update UI. Unfortunately though, the clients only get back the information they send to the server. If two clients connect and they are both talking to the server they do not get the information back from each other. So they can't really chat. This is a problem but I'm sure you guys can figure it out! If you can't then maybe I'll make another tutorial about how to do that.

Thanks so much for reading, I hope that this makes sense. Please leave a comment to let me know that I can do to improve this or my other hubs regarding building a java server!

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Brayan Byrdsong 

      2 years ago from Atlanta, Georgia

      https://www.youtube.com/watch?v=Aw_6HhNcqoM&fe... A video I made showing off how to make a simple lan server easily using similar concepts

    • profile image

      Manikya 

      2 years ago

      Really helpful, please make further parts of the tutorial.

    • profile image

      JT 

      4 years ago

      Love the way you explains things and use nice examples to work through something so many people make difficult. Real talk. VERY GOOD

    • profile image

      Brayan Byrdsong 

      4 years ago from Atlanta, Georgia

      Can you make a tutorial of how to make is so that when Client 1 talks to the server Client 2 receives the information as well?

    • profile image

      gwu 

      5 years ago

      Straight forward tutorial. The code works great. Will expand it to build a monitoring system for all the programs running on several computer. Eventually will add some alarms.

    • profile image

      Darrel 

      5 years ago

      This tutorial is really awesome and easy to follow. I just keep getting an "Address in use" error. Any reason why that is happening?

    • profile image

      Chick 

      5 years ago

      Where is the rest of the tutorial?

      With the client tchat ?

    • profile image

      Majd 

      5 years ago

      Gooood Tutorial

    • Drenguin profile imageAUTHOR

      Drenguin 

      6 years ago from Somewhere

      Wow! Nice catch, I guess I missed then when I was changing the code. I've edited that out now.

      I think I will add a new tutorial about how to get multiple people to chat. My problem is that I'm finding it very hard to explain concepts with just text. I think that I will be adding videos to these tutorials so I can better explain what is going on.

      As for your guess, you are on the right track, that is the general idea. As for how to do it, wait for the next tutorial (hopefully with video)!

    • MyWebs profile image

      Anthony Goodley 

      6 years ago from Sheridan, WY

      I will preface this comment by saying that I have not yet tried out the code, I just read through it all to try to understand and learn from it.

      I noticed one part that puzzles me:

      while(true) {

      }

      Should there be something in that while loop? Otherwise why is there an empty while loop there?

      I'm disappointed that this code doesn't really allow two or more people to chat. Since I'm very new to Java I doubt I'll be able to figure it out on my own. :(

      I would guess that you would need an array to store each user in and broadcast each chat message to everyone except the one who said it otherwise they would end up seeing their own message twice. How to do this if this is the proper solution?

    • Drenguin profile imageAUTHOR

      Drenguin 

      6 years ago from Somewhere

      Thanks for commenting! I'm glad you enjoyed it.

    • dwachira profile image

      [ Danson Wachira ] 

      6 years ago from Nairobi, Kenya

      This is a nice hub Drenguin, i'll look forward to read more of your programming hubs. Thanks for sharing.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com 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: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    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 googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    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)
    Marketing
    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.
    Statistics
    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)