Java Programming - Lesson 26

How to Build a Java Network Chat Application Using TCP/IP Sockets

Have you ever wondered how two separate computer applications exchange messages over a network?

In this lesson, we take an exciting step towards understanding network programming by connecting our Java chat graphical user interface (GUI) to an actual TCP/IP network connection.

In the previous lesson, we learned how to send messages through a Java Writer and receive messages using a BufferedReader. We tested the communication process with the computer's console.

Now, we will replace the console with a network connection and build a simple client-server chat application.

By the end of this tutorial, you should understand how two Java applications can communicate with each other through TCP sockets.

1. What Is TCP/IP Networking?

TCP/IP refers to the family of communication protocols used by computers to exchange information across networks.

Two important protocols in this family are:

Internet Protocol (IP): Responsible for addressing and routing packets between network devices.

Transmission Control Protocol (TCP): Provides a reliable, ordered stream of bytes between communicating applications.

TCP is particularly useful for applications such as chat programs because messages need to arrive reliably and in the correct order.

Our Java chat application will use TCP sockets to establish communication between a client and a server.

2. Understanding the Client-Server Architecture

Most network applications use a client-server arrangement.

A server waits for incoming connections, while a client initiates a connection to the server.

Think of a telephone conversation:

One person waits for an incoming call.

Another person makes the call.

Once the call is established, both people can communicate.

The same basic idea applies to our Java chat application.

The Server

The server listens for incoming connections.

It creates a ServerSocket and waits for a client to connect.

The Client

The client initiates the connection.

It creates a Socket using the server's address and port number.

Once the connection is established, both sides can exchange information.

3. Understanding IP Addresses and Port Numbers

Before a client can connect to a server, it needs two important pieces of information.

IP Address

An IP address identifies a network interface or host.

For example:

127.0.0.1


This is the IPv4 loopback address. It directs communication back to the same computer.

It is commonly used for local testing.

Another example is:

192.168.1.10


This is an example of a private IPv4 address that might be assigned to a computer on a home or office network.

Port Number

A port number identifies the application endpoint on the computer.

Our demonstration uses:

1234


The client must connect to the same port on which the server is listening.

A simple way to remember the difference is:

IP address: identifies the destination computer or network interface.

Port number: identifies the destination application endpoint.

4. Creating a Java TCP Server

Java provides the ServerSocket class for listening for incoming TCP connections.

First, import the class:

import java.net.ServerSocket;


Then create the server socket:

ServerSocket server = new ServerSocket(1234);


This instructs Java to listen for TCP connections on port 1234.

Next, we wait for a client:

Socket socket = server.accept();


The accept() method blocks until a client successfully connects.

When a connection arrives, Java returns a Socket object representing the established communication channel.

The distinction is important:

Java Class

Purpose

ServerSocket

Listens for incoming connections.

Socket

Represents an established connection.


5. Creating a Java TCP Client

The client connects to the server using its address and port number.

For our local demonstration:

Socket socket = new Socket("127.0.0.1", 1234);


This attempts to connect to a server listening on port 1234 on the same computer.

The required import is:

import java.net.Socket;

If the server is running and accepting connections, the connection can be established.

If the server is unavailable, the connection attempt will fail.

This is why we start the server before running the client.

6. Receiving Messages Through a Socket

Once the connection is established, we need to receive messages from the other application.

The socket provides an input stream through:

socket.getInputStream();


This stream supplies incoming bytes.

To work conveniently with text, we wrap it in an InputStreamReader and then a BufferedReader.

BufferedReader input = new BufferedReader(

    new InputStreamReader(socket.getInputStream())

);


Required imports:

import java.io.BufferedReader;

import java.io.InputStreamReader;


Let's understand the classes:

InputStream receives bytes.

InputStreamReader converts bytes into characters.

BufferedReader provides convenient character-reading methods.

We can now receive an entire line of text using:

String message = input.readLine();


For continuous communication, we use a loop:

String message;


while ((message = input.readLine()) != null) {


    chat.appendText(message);


}


The loop continues as messages arrive.

When the other side closes its output stream, readLine() eventually returns null, indicating the end of the input stream.

7. Sending Messages Through a Socket

To send messages, we obtain the socket's output stream:

socket.getOutputStream();


Because the stream works with bytes, we wrap it in an OutputStreamWriter.

Writer output = new OutputStreamWriter(

    socket.getOutputStream()

);


Required imports:

import java.io.Writer;

import java.io.OutputStreamWriter;


Our chat interface can now use this writer to send messages.

For example:

output.write(message + System.lineSeparator());

output.flush();


The write() method sends the message to the output stream.

The flush() method forces buffered output to be passed onward.

The use of a writer allows our chat interface to remain independent of the specific output destination.

It does not need to know whether it is communicating with the console, a file, or a network connection.

8. Connecting the Network Streams to the Chat GUI

We already developed a chat interface in Lesson 25.

That interface accepts a Writer and uses an action listener to capture messages entered by the user.

It also contains an appendText() method for displaying incoming messages.

We can now connect the interface to our socket:

ChatUI chat = new ChatUI(output);


The interface sends messages through the supplied network writer.

When incoming messages arrive, the receiving loop calls:

chat.appendText(message);


The message is then displayed in the chat window.

This gives us a simple but effective way to connect our graphical interface to a network communication channel.

9. Why SwingUtilities.invokeLater() Is Important

There is an important threading issue when building network-enabled Swing applications.

Swing uses an Event Dispatch Thread (EDT) to process GUI events and update interface components.

Network operations, however, may take place on separate background threads.

For example, a thread waiting for an incoming message may receive data while the user is interacting with the GUI.

We should not directly update Swing components from an arbitrary background thread.

Instead, our appendText() method should schedule the update using:

SwingUtilities.invokeLater();


For example:

public void appendText(final String message) {


    SwingUtilities.invokeLater(new Runnable() {


        @Override

        public void run() {


            chatText.append(message + "\n");


        }


    });


}


This schedules the update on the EDT.

Important: Network operations such as accept() and readLine() can block while waiting. They should also run outside the EDT to prevent the application from freezing.

10. Running the Client and Server in NetBeans

Our project contains three executable components:

The test application.

The server application.

The client application.

For this exercise, we will run the server and client rather than the test application.

Step 1: Run the Server

In NetBeans:

Locate the server source file.

Right-click it.

Select Run File.

Allow the server to start listening for connections.

Step 2: Run the Client

Next:

Locate the client source file.

Right-click it.

Select Run File.

Allow the client to connect to the server.

Once the connection succeeds, both applications should display their chat windows.

Step 3: Test Communication

Type a message in the client window and press Enter.

The message should appear in both the client and server chat windows.

Now type a message in the server window.

It should appear in both windows as well.

Congratulations! You have successfully established two-way communication between two Java chat applications.

11. Connecting Two Different Computers

In the demonstration, both applications run on the same computer using:

127.0.0.1


However, we can adapt the application to communicate across two different computers.

The server computer must run the server application.

The client must use the server computer's actual network address.

For example:

Socket socket = new Socket("192.168.1.10", 1234);


The address above is only an example.

To connect successfully, the following conditions must be satisfied:

Both computers must have network connectivity.

The server must be listening on the specified port.

The client must use the correct server IP address or hostname.

The network must allow communication through the selected port.

Firewall settings must not block the connection.

For computers on different networks, additional network configuration may be required.

12. Important Networking Concepts to Remember

Before moving on, let's review the key concepts.

Concept

Meaning

TCP/IP

Protocol family used for network communication.

TCP

Reliable, ordered byte-stream transport protocol.

IP address

Identifies a network destination.

Port number

Identifies an application endpoint.

ServerSocket

Listens for incoming TCP connections.

Socket

Represents an established TCP connection.

InputStream

Receives bytes.

OutputStream

Sends bytes.

InputStreamReader

Converts incoming bytes into characters.

OutputStreamWriter

Converts characters into outgoing bytes.

BufferedReader

Reads buffered character data.

Writer

Sends character data.


A Note About Message Boundaries

TCP provides a continuous stream of bytes rather than separate messages.

In our demonstration, we use line separators to mark the end of each text message, while readLine() reads up to the next line separator.

This is a simple form of message framing.

Real-world network applications must define how messages are separated or how message lengths are communicated.

13. Practical Exercises

Test your understanding with these activities:

Exercise 1: Create a Java server that listens on port 1234.

Exercise 2: Create a Java client that connects to the server using 127.0.0.1.

Exercise 3: Use BufferedReader to receive messages from the socket.

Exercise 4: Use OutputStreamWriter to send messages through the socket.

Exercise 5: Connect both applications to the chat GUI developed in the previous lessons.

Exercise 6: Test two-way communication by sending messages from both applications.

Advanced Challenge: Run the server on one computer and modify the client to connect to it from another computer on the same local network.

Conclusion

We have now moved beyond simulated console communication and successfully connected our Java chat interface to an actual TCP/IP network.

By understanding the client-server model, IP addresses, port numbers, sockets, readers, writers, and Swing threading, we have built the foundation for a functional network-enabled chat application.

The most important achievement is that two separate Java applications can now exchange text messages in both directions through a network connection.

This knowledge is useful far beyond chat applications. The same networking principles form the foundation of many client-server systems, including web applications, messaging platforms, remote services, and other distributed applications.

Keep learning, keep experimenting, and continue developing your programming skills!

Comments