0% found this document useful (0 votes)
10 views12 pages

NguyenTanBaoLe Lab1c

The document outlines a lab assignment for a computer networking course, focusing on socket programming in Java to create a chat application. It includes exercises for downloading a webpage, designing a user interface for the chat application, and implementing a multi-threaded server-client model for concurrent communication. The document provides detailed instructions and code examples for each exercise.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

NguyenTanBaoLe Lab1c

The document outlines a lab assignment for a computer networking course, focusing on socket programming in Java to create a chat application. It includes exercises for downloading a webpage, designing a user interface for the chat application, and implementing a multi-threaded server-client model for concurrent communication. The document provides detailed instructions and code examples for each exercise.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

VIETNAM NATIONAL UNIVERSITY - HO CHI MINH CITY

HO CHI MINH CITY UNIVERSITY OF TECHNOLOGY

CO3094
COMPUTER NETWORK (LAB)
LAB 1
SOCKET PROGRAMMING IN JAVA:
CHAT APPLICATION

LỚP CC05 --- Semester 241


LECTURER: Nguyễn Mạnh Thìn

Student Fullname: Nguyễn Tấn Bảo Lễ


Student ID: 2252428

Ho Chi Minh City – 2024


Ho Chi Minh City University of Technology - HCMUT

Table of contents
1. Socket programming in Java....................................................................................3
Exercise 1: Create a program that connects to a web server and downloads the
homepage of this website to a local computer........................................................... 3
2. Develop a simple chat application using client-server model................................4
Exercise 2: Design the user interface for the chat application...................................4
3. Multithread in Java................................................................................................... 6
Exercise 3: Using a multi-thread programming model to make the chat application
can talk to many different users concurrently............................................................ 6

2
Ho Chi Minh City University of Technology - HCMUT

1. Socket programming in Java


Exercise 1: Create a program that connects to a web server and downloads the
homepage of this website to a local computer.
Steps to run this program:
1. Create a file named the same as the class downloadPage in the folder name
“normal”
2. Compile it by “javac downloadPage.java”
3. Run it by “java downloadPage”
4. The result (a recently created HTML file) will appear in the folder.
package normal;
import java.io.*;
import java.net.*;

public class downloadPage {

public static void main(String[] args) {


String website = "www.google.com"; // Target website

try {
// Get the InetAddress of the website
InetAddress inetAddress = InetAddress.getByName(website);

// Establish connection to the web server on port 80 (HTTP)


Socket socket = new Socket(inetAddress, 80);

// Create input and output streams for the connection


PrintWriter out = new PrintWriter(socket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Send an HTTP GET request


out.println("GET / HTTP/1.1");
out.println("Host: " + website);
out.println("User-Agent: Mozilla/5.0");
out.println("Connection: close");
out.println(); // Blank line indicates end of headers

// Prepare a file to save the homepage content


BufferedWriter writer = new BufferedWriter(new
FileWriter("homepage.html"));

// Read the server's response and write it to a file


String line;
boolean contentStarted = false; // Flag to detect when headers

3
Ho Chi Minh City University of Technology - HCMUT

are over
while ((line = in.readLine()) != null) {
if (contentStarted) {
// Skip lines that are purely numeric (e.g., "5314")
if (!line.matches("\\d+") && !line.isEmpty()) {
writer.write(line);
writer.newLine();
}
}
// Check for the empty line indicating the end of headers
if (line.isEmpty()) {
contentStarted = true;
}
}

// Close all streams and the socket


writer.close();
in.close();
out.close();
socket.close();

System.out.println("Homepage downloaded successfully.");

} catch (UnknownHostException e) {
System.out.println("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
}

2. Develop a simple chat application using


client-server model
Exercise 2: Design the user interface for the chat application
Steps to run this program:
1. Create a file named the same as the class.
2. Compile it by “javac ChatApplicationUI.java”
3. Run it by “java ChatApplicationUI”
4. The result is a new window popup.

4
Ho Chi Minh City University of Technology - HCMUT

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChatApplicationUI {


private JFrame frame;
private JTextArea messageDisplayArea;
private JTextField messageInputField;
private JButton sendButton;
private JLabel connectionStatus;

public ChatApplicationUI() {
frame = new JFrame("Chat Application");

// Message display area (non-editable)


messageDisplayArea = new JTextArea();
messageDisplayArea.setEditable(false);
messageDisplayArea.setLineWrap(true);
messageDisplayArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(messageDisplayArea);

// Message input field


messageInputField = new JTextField();
messageInputField.setColumns(40);

5
Ho Chi Minh City University of Technology - HCMUT

// Send button
sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Here, you can define the action for sending the message
String message = messageInputField.getText();
if (!message.isEmpty()) {
messageDisplayArea.append("You: " + message + "\n");
messageInputField.setText(""); // Clear input field after
sending
}
}
});

// Connection status
connectionStatus = new JLabel("Connected");

// Layout setup
JPanel panel = new JPanel(new BorderLayout());
panel.add(scrollPane, BorderLayout.CENTER);

JPanel inputPanel = new JPanel(new FlowLayout());


inputPanel.add(messageInputField);
inputPanel.add(sendButton);

panel.add(inputPanel, BorderLayout.SOUTH);
panel.add(connectionStatus, BorderLayout.NORTH);

frame.add(panel);
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {


new ChatApplicationUI(); // Launch the chat UI
}
}

3. Multithread in Java
Exercise 3: Using a multi-thread programming model to make the chat
application can talk to many different users concurrently.
The application includes two user interface: server and client.
First, we implement the server:

6
Ho Chi Minh City University of Technology - HCMUT

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

public class ChatServer {


private static Set<ClientHandler> clientHandlers = new
HashSet<>();
private static final int PORT = 12345;

public static void main(String[] args) {


System.out.println("Server is running...");

try (ServerSocket serverSocket = new


ServerSocket(PORT)) {
while (true) {
// Accept client connections
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " +
clientSocket.getInetAddress());

// Create a new handler for the client and


start a thread for it
ClientHandler clientHandler = new
ClientHandler(clientSocket);
clientHandlers.add(clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
System.out.println("Error starting the server: " +
e.getMessage());
}
}

// Broadcast the message to all connected clients


public static synchronized void broadcastMessage(String
message) {
for (ClientHandler clientHandler : clientHandlers) {
clientHandler.sendMessage(message);
}

7
Ho Chi Minh City University of Technology - HCMUT

// Remove a client handler from the list


public static synchronized void removeClient(ClientHandler
clientHandler) {
clientHandlers.remove(clientHandler);
}
}

class ClientHandler implements Runnable {


private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

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

String message;
while ((message = in.readLine()) != null) {
System.out.println("Received: " + message);
// Broadcast the message to all clients
ChatServer.broadcastMessage(message);
}
} catch (IOException e) {
System.out.println("Client disconnected: " +
e.getMessage());
} finally {
try {
clientSocket.close();

8
Ho Chi Minh City University of Technology - HCMUT

} catch (IOException e) {
System.out.println("Error closing the socket:
" + e.getMessage());
}
ChatServer.removeClient(this);
}
}

// Send a message to this client


public void sendMessage(String message) {
out.println(message);
}
}

The server can create a port for clients joining in and sending messages into one
boxchat.
Next, we implement the client interface with the chat application user interface:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClient {


private JFrame frame;
private JTextArea messageDisplayArea;
private JTextField messageInputField;
private JButton sendButton;
private JLabel connectionStatus;
private Socket socket;
private PrintWriter out;
private BufferedReader in;

public ChatClient(String serverAddress, int port) {


frame = new JFrame("Chat Application");

// Message display area (non-editable)


messageDisplayArea = new JTextArea();
messageDisplayArea.setEditable(false);

9
Ho Chi Minh City University of Technology - HCMUT

messageDisplayArea.setLineWrap(true);
messageDisplayArea.setWrapStyleWord(true);
JScrollPane scrollPane = new
JScrollPane(messageDisplayArea);

// Message input field


messageInputField = new JTextField();
messageInputField.setColumns(40);

// Send button
sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});

// Connection status
connectionStatus = new JLabel("Not connected");

// Layout setup
JPanel panel = new JPanel(new BorderLayout());
panel.add(scrollPane, BorderLayout.CENTER);

JPanel inputPanel = new JPanel(new FlowLayout());


inputPanel.add(messageInputField);
inputPanel.add(sendButton);

panel.add(inputPanel, BorderLayout.SOUTH);
panel.add(connectionStatus, BorderLayout.NORTH);

frame.add(panel);
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Attempt to connect to the server


connectToServer(serverAddress, port);
}

10
Ho Chi Minh City University of Technology - HCMUT

private void connectToServer(String serverAddress, int


port) {
try {
socket = new Socket(serverAddress, port);
out = new PrintWriter(socket.getOutputStream(),
true);
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

connectionStatus.setText("Connected to " +
serverAddress);

// Start a thread to listen for incoming messages


from the server
new Thread(new IncomingMessagesHandler()).start();
} catch (IOException e) {
connectionStatus.setText("Connection failed: " +
e.getMessage());
}
}

// Send a message to the server


private void sendMessage() {
String message = messageInputField.getText();
if (!message.isEmpty()) {
out.println(message); // Send to the server
messageInputField.setText(""); // Clear input
field after sending
}
}

// Thread to listen for messages from the server


private class IncomingMessagesHandler implements Runnable
{
public void run() {
String message;
try {
while ((message = in.readLine()) != null) {

11
Ho Chi Minh City University of Technology - HCMUT

messageDisplayArea.append(message + "\n");
}
} catch (IOException e) {
connectionStatus.setText("Connection lost: " +
e.getMessage());
}
}
}

public static void main(String[] args) {


// Start the client and connect to localhost on port
12345
new ChatClient("localhost", 12345);
}
}

In this way, the server handles multiple clients, and each client can send and receive
messages in real-time.

12

You might also like