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.


Before we proceed to study Remote Method Invocation, study this exampe of how Methods connect objects in the same JVM:

megaphone
// create 2 objects which do method calls on each other
public class ApplicationRunner{ public static void main(String [] args){ Cat c1 = new Cat("Ralph"); System.out.println("We have created a cat named " + c1.CatName); Hat h1 = c1.findAPlaceToHide("Suzie's Hat "); System.out.println( c1.CatName + " is now hiding in Hat " + Hat.hatName ); System.out.println("The cat is OK " + h1.wellnessCheckForCat()); } }
class Cat{ public String CatName; public Hat hatName; public Cat(String name){ this.CatName = name; }
public Hat findAPlaceToHide(String HatName){ this.hatName = new Hat(HatName); this.hatName.hidingPlaceForACat = this; return this.hatName ; } }
class Hat{ // data field : public Hat(String hName){this.hatName = hName;}
public static String hatName; public static Cat hidingPlaceForACat;
public static boolean wellnessCheckForCat(){ if (hidingPlaceForACat !=null) {return true;} return false; } }
minus

As we proceed from understanding sockets toward building Enterprise Java Beans (EJB), the next logical step would be to deepen our understanding of *network protocols* and *client-server architecture*, followed by an exploration of *Remote Method Invocation (RMI)*.

These concepts serve as the foundation for distributed computing in Java, and they will allow us to grasp the mechanisms behind EJB’s operation in enterprise applications.

### Next Steps on the Journey to EJB
1. Network Protocols and Client-Server Architecture - Building on the basics of sockets, learning how higher-level protocols like HTTP and TCP/IP manage communication between clients and servers is essential. Understanding these protocols gives insight into the ways data travels across networks and helps make sense of how EJBs leverage them for efficient communication. - Explore practical exercises to set up a basic client-server model in Java, using sockets to simulate request-response communication.
2. Java Networking Libraries and HTTP Communication - While sockets provide low-level control, Java offers libraries like `java.net` to simplify network communication. Learning to use Java’s HTTP libraries for communication between applications will lay the groundwork for understanding how EJB components communicate with other services or APIs in an enterprise system. - Experiment with HTTP connections and RESTful APIs in Java, which will ease the transition to creating, deploying, and managing enterprise beans that rely on networked data exchanges.
3. Remote Method Invocation (RMI)
- RMI is a natural progression from sockets because it abstracts away much of the complexity involved in direct socket communication.
RMI allows Java programs to invoke methods on objects located on remote servers as if they were local.
This distributed object model is central to EJB, as it lets enterprise beans communicate across a network.
- A practical exercise here could involve building a small RMI-based client-server application where a client calls remote methods on a server. This will illuminate the principles of remote invocation, object serialization, and the dynamic loading of classes – all fundamental to EJB.
4. Java Naming and Directory Interface (JNDI) - JNDI is crucial for enterprise applications because it provides a centralized directory for looking up and accessing resources like databases, message queues, and other EJBs. JNDI enables EJB clients to locate and connect to EJBs within a complex distributed system. - A useful next step would be to understand how to set up and retrieve objects using JNDI in Java. Experiment with basic directory lookups and resource bindings, which will be critical for configuring and managing EJBs.
5. Understanding Java EE Components and Containers - Moving from networking basics, you’ll want to get familiar with the Java Enterprise Edition (Java EE) framework, especially the concept of containers. EJBs live within a container environment, which handles lifecycle management, security, transactions, and resource pooling. - Explore how containers work, focusing on the roles of the EJB container, web container, and application server. This will provide a more practical sense of the runtime environment in which EJBs operate.
6. Enterprise JavaBeans Basics and Session Beans - Finally, start with a gentle introduction to the EJB specification itself, especially session beans (stateless and stateful) which are foundational in enterprise Java development. Understanding session beans will prepare you to build more complex EJBs, as they serve as the “entry-level” components in the EJB ecosystem. - Develop simple EJBs that perform basic business logic in a Java EE application server, then progress to more complex operations, such as handling transactions and managing session states.
### Practical Lab Sequence for Mastery
A well-sequenced set of labs might follow this progression: 1. Implement a basic client-server model using sockets. 2. Communicate between applications using HTTP in Java. 3. Create and invoke remote methods using Java RMI. 4. Set up and retrieve resources using JNDI. 5. Deploy a simple session bean on an EJB container.
By systematically building on each of these core topics, you’ll establish the technical depth needed to effectively use EJB in enterprise applications, preparing you for larger, transactional, and highly scalable Java-based systems.

ok

Next Steps:

Create a simple client-server application using Java sockets.
This exercise will reinforce the principles of network communication at a foundational level, allowing students to understand direct, low-level communication between two programs.

Lab: Create a simple client-server application using Java sockets .
This exercise will reinforce the principles of network communication at a foundational level, allowing students to understand direct, low-level communication between two programs.
---
Activity: Building a Simple Client-Server Application with Java Sockets
1. **Objective**: To establish a basic understanding of client-server communication using sockets in Java.
2. **Instructions**: - **Server-Side Setup**: - Write a Java program that acts as a server. This program will: - Open a socket on a specified port. - Listen for incoming client connections. - Accept a connection from a client, receive a simple message (e.g., "Hello Server!"), and send back a response (e.g., "Hello Client!"). - Close the connection after responding. - Example Code Outline for the Server: ```java import java.io.*; import java.net.*;
public class SimpleServer { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(12345)) { // Specify the port System.out.println("Server is listening on port 12345"); while (true) { Socket socket = serverSocket.accept(); System.out.println("Client connected");
InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String message = reader.readLine(); System.out.println("Received from client: " + message);
OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output, true); writer.println("Hello Client!");
socket.close(); } } catch (IOException ex) { System.out.println("Server error: " + ex.getMessage()); } } } ```
- **Client-Side Setup**: - Write a Java program that acts as a client. This program will: - Connect to the server using its IP address and the specified port. - Send a simple message (e.g., "Hello Server!") to the server. - Wait to receive a response from the server and print it to the console. - Example Code Outline for the Client: ```java import java.io.*; import java.net.*;
public class SimpleClient { public static void main(String[] args) { String hostname = "localhost"; // Change if running on different machines int port = 12345; try (Socket socket = new Socket(hostname, port)) { OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output, true); writer.println("Hello Server!");
InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String response = reader.readLine(); System.out.println("Received from server: " + response); } catch (IOException ex) { System.out.println("Client error: " + ex.getMessage()); } } } ```
3. Expected Outcome - The server program should print “Client connected” and display the message it received. - The client program should print the response it received from the server, e.g., “Received from server: Hello Client!”
4. Reflection - Have students reflect on the structure of the client and server, focusing on the roles of IP, port, and data streams in socket communication. - Discuss potential real-world applications and limitations of direct socket communication.
---
This activity will prepare students to appreciate the underlying mechanics of network communication before they explore more abstracted and sophisticated networking models, such as RMI and EJBs.
megaphone

Next Steps: Let’s learn how to create Java Server Pages JSP and make a Web Page Chat client.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.