Skip to content
Share
Explore

J2EE Lab 1 : Sockets and a Chat CLIENT

Table of Contents
This series of Labs will build us up to creating Web Applications with Model View Controller and Service Oriented Architecture components.
Lab 0: Cat in the Hat review of how objects communicate with the same JVM using Method Calls
Now, what about the case of connecting OBJECTS that live in different Java Virtual Machines connected via TCP IP network pipes.
Lab 1: Sockets and the theory of connecting Java Objects over a TCP IP Network

Learning Outcomes:

Java J2EE Java Enterprise Edition lab to introduce the use of Sockets: a server program and a client connecting to the server.

=> Demonstrate creating a simple Chat Client

error

Today we’ll discuss sockets, a concept foundational to network communication in computer systems.

Sockets are interfaces through which data flows between different computers across a network.

To understand sockets, we need to look beyond technology and consider examples from everyday life where similar connections enable information transfer.

### The Everyday Example: Postal Mail

Imagine two individuals, Sarah and Tom, who want to exchange letters.
Sarah writes a letter, places it in an envelope, addresses it, and sends it off through the postal service.
Tom, at the other end, has a specific address where he can receive this letter. In this case:
- Sarah is like the *client* computer. - Tom’s mailbox is the *server* ready to receive the message. - The envelope serves as a *packet* of data. - The post office network represents the internet or any network facilitating the transfer. A socket, in this analogy, is akin to the unique addresses on Sarah and Tom’s envelopes. Each socket is defined by two main components: an IP address (which identifies the computer) and a port number (which identifies the specific application or service within the computer).

### Practical Example: A Telephone Call

Consider a phone call. When you dial someone’s number, you’re not calling a specific device per se but rather a *unique endpoint* on the network.
This endpoint, like a socket, connects the two phones (or computers) in a way that they can send and receive data (in this case, sound) seamlessly.
In network terms: ​- The phone number is like the IP address. - Different extensions in a large company might represent different ports, allowing various departments to handle different types of calls or data.

How Sockets Work in Networking

In computing, sockets function similarly by allowing two applications to connect and communicate.

The client application creates a socket, attaches it to an IP and port, and sends a request.

We will need to learn some basic networking concepts as we proceed:
PORT
Internet Protocol IP Addresses: Numbers which identify NIA network interface adapters on a network. Not that the operating system which creates and manages the IP Stack can have (and in general WILL have) more than one network interface adapter.
Open a Command Terminal Window and type:
cmd > ipconfig /all

The server, listening on that IP and port, accepts the request, establishing a connection.

From that point, both parties can exchange data back and forth over the network.


Let’s return to the example of Tom and Sarah, but imagine instead they’re sending frequent messages back and forth. To avoid the hassle of addressing every letter, they might open a shared "communication line," such as a phone line. Similarly, once a socket connection is established between computers, it enables continuous data transfer, much like an open phone line allows an ongoing conversation.

Types of Sockets

1. TCP Sockets – This type of socket is like a reliable messenger service. Think of it as registered mail where delivery is guaranteed. TCP (Transmission Control Protocol) ensures that data packets arrive in the correct order and without errors, making it suitable for applications like web browsing, emails, and file transfers where accuracy is critical.

2. UDP Sockets – This type operates like a regular post where delivery isn’t guaranteed. UDP (User Datagram Protocol) is faster but does not ensure that data arrives intact or in order. It’s ideal for applications like online gaming, video streaming, or VoIP calls, where speed matters more than perfect accuracy.
### Bringing It All Together: A Quick Recap
A socket in networking is akin to a unique point of connection, like a telephone extension or a unique address on a letter.
It enables two computers to connect in a way that allows them to communicate and exchange data, efficiently and effectively.
Just as we rely on phone numbers and mailing addresses to reach specific individuals, computers use IP addresses and port numbers to direct network traffic to the correct application and device.
In essence, a socket is the technological equivalent of a trusted handshake between two parties in the digital world, enabling structured, purposeful communication.

We will be using Sublime Text Editor and compiling our programs at the command line.
image.png
Lab Exercise 1: Creating a Simple Chat Client Using Java Sockets in J2EE
This lab will guide students through creating a basic chat client using Java sockets, enabling real-time communication between a client and a server.
The client program will connect to the server, and both programs will exchange messages.
This fundamental exercise will introduce students to network programming, specifically utilizing sockets to create a reliable, bidirectional communication channel.

Lab Objectives

By the end of this lab, students will be able to:
Create a server program that listens for incoming client connections using Java sockets.
Develop a client program that connects to the server.
Implement simple message exchange between the client and server.
Understand fundamental concepts of network programming, including socket communication, ports, and I/O input output streams.

Prerequisites

Familiarity with Java programming (loops, conditionals, classes, and methods).
Basic understanding of J2EE (Java 2 Platform, Enterprise Edition).
Basic knowledge of network concepts (e.g., client-server architecture, IP, and ports).

Part 1: Setting Up the Server

Step 1.1: Create the Server Class

Now we are introducing the concept of Multi Threaded Programming.
The server program will accept multiple connections and handle each client in a separate thread.
The server will run on a specified port and wait for clients to connect.
Code: Server.java
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class Server {
private static final int PORT = 12345;
private static List<ClientHandler> clients = new ArrayList<>();

public static void main(String[] args) {
System.out.println("Server started...");
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);
ClientHandler clientHandler = new ClientHandler(clientSocket);
clients.add(clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

// Broadcast message to all clients
public static void broadcastMessage(String message, ClientHandler sender) {
for (ClientHandler client : clients) {
if (client != sender) {
client.sendMessage(message);
}
}
}
}

Step 1.2: Create the ClientHandler Class

The ClientHandler class will handle individual client connections.
It will read messages from the client and broadcast them to all other connected clients.
Code: ClientHandler.java
import java.io.*;
import java.net.*;

public class ClientHandler implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;

public ClientHandler(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
try {
// Setting up input and output streams
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

// Broadcast messages received from client
String message;
while ((message = in.readLine()) != null) {
System.out.println("Received: " + message);
Server.broadcastMessage(message, this);
}
} catch (IOException e) {
System.err.println("Connection error: " + e.getMessage());
} finally {
closeConnection();
}
}

// Send message to this client
public void sendMessage(String message) {
out.println(message);
}

// Close connections
private void closeConnection() {
try {
if (in != null) in.close();
if (out != null) out.close();
if (socket != null) socket.close();
} catch (IOException e) {
System.err.println("Error closing connection: " + e.getMessage());
}
}
}

Part 2: Setting Up the Client

The client program will connect to the server, send messages, and receive broadcast messages from other clients.

Step 2.1: Create the Client Class

The client connects to the server using a socket and establishes input and output streams for sending and receiving messages.
Code: Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
private static final String SERVER_ADDRESS = "127.0.0.1"; // Server IP
private static final int SERVER_PORT = 12345;

public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)) {

System.out.println("Connected to the chat server!");

// Start a thread to listen for messages from the server
Thread readThread = new Thread(() -> {
try {
String serverMessage;
while ((serverMessage = in.readLine()) != null) {
System.out.println("Server: " + serverMessage);
}
} catch (IOException e) {
System.err.println("Connection closed by server.");
}
});
readThread.start();

// Sending messages to the server
while (true) {
System.out.print("You: ");
String message = scanner.nextLine();
out.println(message);
}

} catch (IOException e) {
e.printStackTrace();
}
}
}

Part 3: Running the Server and Client Programs

Start the Server:
image.png
Compile and run the Server.java program first to start the server.
The server will listen on port 12345 for incoming client connections.
javac Server.java ClientHandler.java
java Server

Run the Client:
Compile and run the Client.java program to start a client.
You can open multiple terminal windows and run Client.java multiple times to simulate multiple clients connecting to the server.
javac Client.java
java Client

Testing the Chat Application:
Each client should be able to send a message that will be received by all other clients.
Type messages in the client terminal, and they will be broadcast to all connected clients.

Part 3: Testing the Chat Application

Step 1: Start the Server

Run the ChatServer program.
Ensure the server is running and listening on the specified port.

Step 2: Start Multiple Client Instances

Run multiple instances of the ChatClient program.
Connect each client to the server and observe how messages from one client are broadcast to all other clients connected to the server.

Step 3: Send and Receive Messages

Each client can send messages, which will be displayed to all connected clients.
Observe the functionality of the chat application and verify that all clients are receiving broadcast messages.

Additional Exercises

Enhance Message Formatting: Add a username feature to identify the sender in each message.
Implement Private Messaging: Allow clients to send private messages to specific users by implementing command syntax (e.g., /msg username message).
Add Connection Limits: Implement a maximum number of clients that the server can support.
Exception Handling: Improve error handling to gracefully disconnect clients when errors occur.

Conclusion

This lab provides a fundamental understanding of socket programming in Java, showcasing the creation of a basic chat application. Through this exercise, students gain experience in real-time communication protocols and threading, both essential skills in network programming.

Additional Exploration

To further enhance the chat client:
Add Nicknames: Allow each client to set a nickname and display it alongside messages.
Exit Option: Implement a way for clients to type "exit" to leave the chat.
GUI Enhancement: Use Swing to create a graphical user interface for the chat application, adding an intuitive chat window.
Security: Introduce basic encryption for messages.

Lab Report Questions

Explain the role of ServerSocket and Socket in the client-server architecture.
What are input and output streams, and how do they enable communication between the client and server?
Discuss potential limitations of this basic chat client and suggest improvements.
This concludes the lab on Java socket programming, our first exercise in networking within Java J2EE.
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.