Share
Explore

Java Chat Client Lab Workbook

Objective

This lab will guide you to develop a simple TCP-based chat application in Java. By the end of this lab, you should have an understanding of Java network programming, thread usage, and GUI creation.

Prerequisites

Before proceeding with this lab guide, you must have a basic understanding of:
Java Programming
Basics of Networking
Java Swing for GUI (optional, since the GUI part is explained)

Lab Components

This lab consists of the following components:
Java Chat Server - A server program that can accept connections from multiple clients.
Java Chat Client - A client program with GUI that users can use to send and receive messages.
Please follow the steps provided for each component.

Component 1: Java Chat Server

javaCopy code
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {

private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
private ArrayList<Socket> clients = new ArrayList<Socket>();

//Constructor for server with port as parameter
public ChatServer(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started");

while(true) {
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// Add the connected client to the list
clients.add(socket);

// Create a new thread for client
Thread t = new ClientHandler(socket, clients);

// Start the thread
t.start();
}

}
catch(IOException i) {
System.out.println(i);
}
}

public static void main(String args[]) {
ChatServer server = new ChatServer(5000);
}
}

In this ChatServer class, the server is started on the specified port, and it keeps listening for incoming connections. When a client connects, the server adds the client's socket to its client list and creates a new thread to handle communication with that client.

Component 2: ClientHandler

javaCopy code
import java.io.*;
import java.util.*;
import java.net.*;

//ClientHandler class
class ClientHandler extends Thread {
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
ArrayList<Socket> clients;

// Constructor
public ClientHandler(Socket s, ArrayList<Socket> clients) throws IOException {
this.s = s;
this.clients = clients;
this.dis = new DataInputStream(s.getInputStream());
this.dos = new DataOutputStream(s.getOutputStream());
}

@Override
public void run() {
String received;
while (true) {
try {
// receive the string
received = dis.readUTF();

System.out.println(received);

// Broadcast message to all clients
for(Socket clientSocket : clients) {
DataOutputStream clientDos = new DataOutputStream(clientSocket.getOutputStream());
clientDos.writeUTF(received);
}

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

try {
// closing resources
this.dis.close();
this.dos.close();

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

The ClientHandler class extends Thread and handles communication with a client. It reads incoming messages from the client and then broadcasts them to all connected clients.

Component 3: Java Chat Client

javaCopy code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatClient extends JFrame implements ActionListener {
// Components of the chat client
private static final long serialVersionUID = 1L;
private JTextField msg_input;
private JTextArea chat_area;
private JButton send;
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;

// constructor to receive the port number
public ChatClient(String address, int port) {
// GUI components
setLayout(new BorderLayout());
// Chat area
chat_area = new JTextArea();
chat_area.setEditable(false);
add(new JScrollPane(chat_area), BorderLayout.CENTER);
// Message input field
msg_input = new JTextField();
add(msg_input, BorderLayout.SOUTH);
msg_input.addActionListener(this);

// Send button
send = new JButton("Send");
add(send, BorderLayout.EAST);
send.addActionListener(this);

setSize(500, 500);
setVisible(true);

// Establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");

// Takes input from the client socket
input = new DataInputStream(socket.getInputStream());

// Sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u) {
System.out.println(u);
}
catch(IOException i) {
System.out.println(i);
}

// Start a new thread for receiving messages
new Thread(new Runnable() {
public void run() {
String line = "";
while (true) {
try {
line = input.readUTF();
chat_area.append(line + "\n");
}
catch(IOException i) {
System.out.println(i);
}
}
}
}).start();

// Send a default welcome message
try {
out.writeUTF("New client joined: " + socket);
}
catch(IOException i) {
System.out.println(i);
}
}

public void actionPerformed(ActionEvent e) {
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.