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

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!

More by this Author


Comments 13 comments

dwachira profile image

dwachira 4 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.


Drenguin profile image

Drenguin 4 years ago from Somewhere Author

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


MyWebs profile image

MyWebs 4 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 image

Drenguin 4 years ago from Somewhere Author

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


Majd 3 years ago

Gooood Tutorial


Chick 3 years ago

Where is the rest of the tutorial?

With the client tchat ?


Darrel 3 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?


gwu 3 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.


Brayan Byrdsong 3 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?


JT 3 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


sonal 7 months ago

this gives an error as not able to identify chatbox variable in in cleintthread class


Manikya 7 months ago

Really helpful, please make further parts of the tutorial.


Brayan Byrdsong 7 months ago from Atlanta, Georgia

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

    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