ĐỀ 1: BIGINTEGER Problem description: Write a program that has 2 sides: Client and Server,
they communicate to each other using TCP socket. They both use port "6abc" where "abc" are 3
last digits of your Student ID. Server:
Server can accept connect from client.
For each client, server has to create a thread that will maintain the connection with that
client (print out a message to screen each time server accepts a connection). Each thread
can do the following actions:
o receives integer number n from client.
o calculates the value of n⁴.
o and sends back the value n⁴ to client.
Client:
Client can connect to server.
Client gets an integer number n from the user (keyboard).
Client sends an integer number n to server.
and client receives the value n⁴ from server, prints this value to the screen.
package Practice1;
import [Link].*; // Thư viện I/O cho DataInputStream, DataOutputStream
import [Link].*; // Thư viện mạng cho ServerSocket, Socket
public class Server1 {
public static void main(String[] args) throws IOException {
int port = 6123;
ServerSocket serverSocket = new ServerSocket(port); // Tạo ServerSocket lắng nghe trên
port
[Link]("Server is waiting for client connections on port: " + port); // Thông báo
server sẵn sàng
int clientCount = 0; // Biến đếm số client đã kết nối
while (true) { // Vòng lặp vô hạn để chấp nhận nhiều client
Socket clientSocket = [Link](); // Chấp nhận kết nối từ client
clientCount++; // Tăng số đếm client
[Link]("Accepted connection from client " + clientCount); // In thông báo
chấp nhận kết nối
// Tạo thread mới để duy trì kết nối và xử lý client này
new PowerThread(clientSocket, clientCount).start();
}
}
// Lớp thread xử lý từng client riêng biệt
static class PowerThread extends Thread {
private Socket socket; // Socket giao tiếp với client
private int clientNumber; // Số thứ tự client
public PowerThread(Socket socket, int clientNumber) { // Constructor thiết lập socket và số
client
[Link] = socket; // Lưu socket
[Link] = clientNumber; // Lưu số
}
@Override
public void run() { // Phương thức run() định nghĩa công việc của thread
try {
// Tạo luồng đọc số từ client
DataInputStream inFromClient = new DataInputStream([Link]());
// Tạo luồng ghi kết quả về client
DataOutputStream outToClient = new DataOutputStream([Link]());
while (true) { // Vòng lặp xử lý nhiều số n từ client
try {
int n = [Link](); // Đọc số nguyên n từ client
long power = (long) [Link](n, 4); // Tính n^4 (dùng long để tránh overflow với
n lớn)
[Link](power); // Gửi kết quả n^4 về client
[Link](); // Đẩy dữ liệu ngay lập tức
} catch (EOFException e) { // Nếu client ngắt kết nối (không gửi nữa)
break; // Thoát vòng lặp
}
}
} catch (IOException e) { // Bắt lỗi I/O
[Link]("Client error" + clientNumber + ": " + [Link]()); // In lỗi
} finally {
try {
[Link](); // Đóng socket client để giải phóng tài nguyên
} catch (IOException e) { // Bắt lỗi đóng socket
[Link](); // In stack trace
}
[Link]("Client #" + clientNumber + " has disconnected."); // In thông báo
ngắt
}
}
}
}
### Client:
package Practice1;
import [Link].*; // Thư viện I/O cho DataInputStream, DataOutputStream, BufferedReader
import [Link].*; // Thư viện mạng cho Socket
public class Client1 {
public static void main(String[] args) throws IOException {
int port = 6123;
// Kết nối tới server localhost trên port
Socket socket = new Socket("localhost", port);
[Link]("Client connected to the server on port: " + port); // Thông báo kết nối thành công
// Tạo luồng ghi số tới server
DataOutputStream outToServer = new DataOutputStream([Link]());
// Tạo luồng đọc kết quả từ server
DataInputStream inFromServer = new DataInputStream([Link]());
// Tạo luồng đọc từ bàn phím
BufferedReader inFromUser = new BufferedReader(new InputStreamReader([Link]));
while (true) { // Vòng lặp cho phép gửi nhiều số n
[Link]("Enter an integer n (type 'quit' to exit): "); // Yêu cầu nhập
String input = [Link](); // Đọc từ bàn phím
if ([Link]("quit")) { // Thoát nếu nhập quit
break;
}
try {
int n = [Link](input); // Chuyển chuỗi thành số nguyên
[Link](n); // Gửi n tới server
[Link](); // Đẩy dữ liệu
long power = [Link](); // Nhận kết quả n^4 từ server
[Link]("n^4: " + power); // In ra console
} catch (NumberFormatException e) { // Nếu nhập không phải số
[Link]("Error: Please enter a valid integer!"); // Thông báo lỗi
}
}
// Đóng tài nguyên
[Link](); // Đóng luồng gửi
[Link](); // Đóng luồng nhận
[Link](); // Đóng luồng đọc bàn phím
[Link](); // Đóng socket
}
}
ĐỀ 2: Problem description: Client send message to mathematics server.
Please write a program in Java that has 2 sides: server and client. Server uses
port 4abcc where abc are 3 last numbers of your student ID.
At server:
1. Server listens to the connection from clients on port 4abcc and accepts them.
2. For each client, server has to create a thread that will maintain the connection with that client
(print out a message to screen each time server accepts a connection).
3. After accepting connection from client, server receives the first client’s message that is
[Student_ID]. Server calculates the 4 times of [Student_ID] and sends that value back to
client. (You should use BigInteger)
4. Server does the loop:
Server receives the client’s message:
- If that message is a positive integer number, server calculates [number]4 and sends that
value back to client (You should use BigInteger).
- If that message is not a positive integer number, server just sends the client's message back to
client.
At client:
1. Client creates a connection to server.
2. After connecting successfully to server, client sends to server the first message that
is [Student_ID], then reads the 1st reply from server (4x[Student_ID]) and prints it out to the
screen.
3. Client does the following loop:
Client continues to read a message from user keyboard and sends that message to server.
If the message read from keyboard is an integer number, client prepares to receive a message
from server that is [number]4 and prints out to the client's screen.
Otherwise, client just receives message from server and prints it out to the screen.
### Server
package Practice3;
import [Link].*;
import [Link];
import [Link].*;
public class MathServer {
// Requirement: Server listens on port 4abcc, abc=126 -> port=41266
private static final int PORT = 41266;
public static void main(String args[]) throws IOException {
ServerSocket listener = null;
// Requirement: Server listens for client connections
[Link]("Server is waiting to accept user...");
try {
listener = new ServerSocket(PORT); // Create server socket on port 41266
} catch (IOException e) {
[Link]("Error starting server: " + e);
[Link](1);
}
try {
int clientNumber = 0;
while (true) {
// Requirement: Accept connection from clients
Socket socketOfServer = [Link]();
// Requirement: Print message when accepting a connection
[Link]("New connection with client# " + clientNumber + " at " + socketOfServer);
// Requirement: Create a thread for each client
new ServiceThread(socketOfServer, clientNumber++).start();
}
} finally {
if (listener != null) {
[Link](); // Close server socket
}
}
}
private static class ServiceThread extends Thread {
private int clientNumber;
private Socket socketOfServer;
public ServiceThread(Socket socketOfServer, int clientNumber) {
[Link] = clientNumber;
[Link] = socketOfServer;
}
@Override
public void run() {
try {
// Initialize input/output streams
BufferedReader is = new BufferedReader(new InputStreamReader([Link]()));
BufferedWriter os = new BufferedWriter(new OutputStreamWriter([Link]()));
// Requirement: Receive first client's message [Student_ID]
String studentIdStr = [Link]();
try {
// Requirement: Calculate 4 times [Student_ID] using BigInteger
BigInteger studentId = new BigInteger(studentIdStr);
BigInteger fourTimesId = [Link]([Link](4));
[Link]([Link]());
[Link]();
[Link]();
} catch (NumberFormatException e) {
// Handle invalid Student_ID
[Link]("Invalid Student ID");
[Link]();
[Link]();
}
// Requirement: Server loops to handle client messages
while (true) {
String message = [Link]();
if (message == null || [Link]("QUIT")) {
[Link]("Client # " + [Link] + " quit!");
break;
}
try {
// Requirement: If message is a positive integer, calculate [number]^4
BigInteger number = new BigInteger(message);
if ([Link]([Link]) > 0) {
BigInteger result = [Link](4); // Calculate [number]^4 using BigInteger
[Link]([Link]());
} else {
// Requirement: If not a positive integer, send back original message
[Link](message);
}
} catch (NumberFormatException e) {
// Requirement: If not an integer, send back original message
[Link](message);
}
[Link]();
[Link]();
}
} catch (IOException e) {
[Link]("Error with client # " + clientNumber + ": " + e);
} finally {
try {
[Link](); // Close client socket
} catch (IOException e) {
[Link](e);
}
}
}
}
}
###Client
package Practice3;
import [Link].*;
import [Link].*;
public class MathClient {
private static final String SERVER_HOST = "localhost";
// Requirement: Connect to server on port 4abcc, abc=126 -> port=41266
private static final int SERVER_PORT = 41266;
// Requirement: First message is Student_ID
private static final String STUDENT_ID = "2201040126";
public static void main(String[] args) {
Socket socketOfClient = null;
BufferedWriter os = null;
BufferedReader is = null;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader([Link]));
try {
// Requirement: Client creates a connection to server
socketOfClient = new Socket(SERVER_HOST, SERVER_PORT);
[Link]("Connected to server at " + SERVER_HOST + ":" + SERVER_PORT);
os = new BufferedWriter(new OutputStreamWriter([Link]()));
is = new BufferedReader(new InputStreamReader([Link]()));
// Requirement: Send first message [Student_ID]
[Link](STUDENT_ID);
[Link]();
[Link]();
// Requirement: Read the 1st reply from server (4x[Student_ID]) and print
String responseLine = [Link]();
[Link]("Server replies 4*StudentID: " + responseLine);
// Requirement: Loop to read from keyboard and send to server
while (true) {
[Link]("Please enter your message (type QUIT to exit):");
String message = [Link]();
[Link](message);
[Link]();
[Link]();
// Requirement: Receive and print server response ([number]^4 or original message)
responseLine = [Link]();
[Link]("Server: " + responseLine);
if ([Link]("QUIT") || responseLine == null) {
break;
}
}
} catch (UnknownHostException e) {
[Link]("Don't know about host " + SERVER_HOST);
} catch (IOException e) {
[Link]("Couldn't get I/O for the connection to " + SERVER_HOST + ": " + e);
} finally {
try {
if (os != null) [Link]();
if (is != null) [Link]();
if (socketOfClient != null) [Link]();
} catch (IOException e) {
[Link]("Error closing resources: " + e);
}
}
}
}
Phép toán Công thức với Code với Công thức với Code với Ghi chú
Integer Integer BigInteger BigInteger
Cộng (Addition) c = a + b int c = a + b; c = [Link](b) BigInteger c = Không giới hạn
[Link](b); với BigInteger.
Trừ c=a-b int c = a - b; c = [Link](b) BigInteger c = Tránh âm với
(Subtraction) [Link](b); Integer lớn.
Nhân c=a*b int c = a * b; c= BigInteger c = BigInteger xử lý
(Multiplication) [Link](b) [Link](b); số lớn tốt hơn.
Lũy thừa c = [Link](a, b) double c = c = [Link](b) BigInteger c = BigInteger
(Power) (trả về double) [Link](a, b); [Link](b); chính xác với số
lớn.
Ước chung lớn gcd(a, b) (tự định int gcd = gcd(a, c = [Link](b) BigInteger c = BigInteger hỗ
nhất (GCD) nghĩa) b); [Link](b); trợ trực tiếp.
Modulus c=a%b int c = a % b; c = [Link](b) BigInteger c = Kết quả dương
(Modulo) [Link](b); với BigInteger.
Giá trị tuyệt đối c = [Link](a) int c = c = [Link]() BigInteger c = Luôn trả về giá
(Absolute) [Link](a); [Link](); trị dương.
package MathProgram;
import [Link].*;
import [Link];
import [Link].*;
public class MathServer {
// Requirement: Server listens on port 4abcc, abc=126 -> port=41266
private static final int PORT = 41266;
public static void main(String args[]) throws IOException {
ServerSocket listener = null;
// Requirement: Server listens for client connections
[Link]("Server is waiting to accept user...");
try {
listener = new ServerSocket(PORT); // Create server socket on port 41266
[Link]("Server successfully bound to port " + PORT);
} catch (IOException e) {
[Link]("Error starting server on port " + PORT + ": " + [Link]());
[Link]();
[Link](1);
}
try {
int clientNumber = 0;
while (true) {
// Requirement: Accept connection from clients
Socket socketOfServer = [Link]();
// Requirement: Print message when accepting a connection
[Link]("New connection with client# " + clientNumber + " at " +
[Link]().getHostAddress());
// Requirement: Create a thread for each client
new ServiceThread(socketOfServer, clientNumber++).start();
}
} finally {
if (listener != null) {
[Link](); // Close server socket
}
}
}
private static class ServiceThread extends Thread {
private int clientNumber;
private Socket socketOfServer;
public ServiceThread(Socket socketOfServer, int clientNumber) {
[Link] = clientNumber;
[Link] = socketOfServer;
}
@Override
public void run() {
try {
// Initialize input/output streams
BufferedReader is = new BufferedReader(new
InputStreamReader([Link]()));
BufferedWriter os = new BufferedWriter(new
OutputStreamWriter([Link]()));
// Requirement: Receive first client's message [Student_ID]
String studentIdStr = [Link]();
try {
// Requirement: Calculate 4 times [Student_ID] using BigInteger
BigInteger studentId = new BigInteger(studentIdStr);
BigInteger fourTimesId = [Link]([Link](4));
[Link]([Link]());
[Link]();
[Link]();
} catch (NumberFormatException e) {
// Handle invalid Student_ID
[Link]("Invalid Student ID");
[Link]();
[Link]();
}
// Requirement: Server loops to handle client messages
while (true) {
String message = [Link]();
if (message == null || [Link]("QUIT")) {
[Link]("Client # " + [Link] + " quit!");
break;
}
try {
// Requirement: If message is a positive integer, calculate [number]^4
BigInteger number = new BigInteger(message);
if ([Link]([Link]) > 0) {
BigInteger result = [Link](4); // Calculate [number]^4 using BigInteger
[Link]([Link]());
} else {
// Requirement: If not a positive integer, send back original message
[Link](message);
}
} catch (NumberFormatException e) {
// Requirement: If not an integer, send back original message
[Link](message);
}
[Link]();
[Link]();
}
} catch (IOException e) {
[Link]("Error with client # " + clientNumber + ": " + e);
} finally {
try {
[Link](); // Close client socket
} catch (IOException e) {
[Link](e);
}
}
}
}
}
###Client
package MathProgram;
import [Link].*;
import [Link].*;
public class MathClient {
private static final String SERVER_HOST = "localhost";
// Requirement: Connect to server on port 4abcc, abc=126 -> port=41266
private static final int SERVER_PORT = 41266;
public static void main(String[] args) {
Socket socketOfClient = null;
BufferedWriter os = null;
BufferedReader is = null;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader([Link]));
try {
// Requirement: Client creates a connection to server
socketOfClient = new Socket(SERVER_HOST, SERVER_PORT);
[Link]("Connected to server at " + SERVER_HOST + ":" +
SERVER_PORT);
os = new BufferedWriter(new OutputStreamWriter([Link]()));
is = new BufferedReader(new InputStreamReader([Link]()));
// Requirement: Read Student_ID from user keyboard
[Link]("Please enter your Student ID:");
String studentId = [Link]();
// Requirement: Send first message [Student_ID]
[Link](studentId);
[Link]();
[Link]();
// Requirement: Read the 1st reply from server (4x[Student_ID]) and print
String responseLine = [Link]();
[Link]("Server: " + responseLine);
// Requirement: Loop to read from keyboard and send to server
while (true) {
[Link]("Please enter your message (type QUIT to exit):");
String message = [Link]();
[Link](message);
[Link]();
[Link]();
// Requirement: Receive and print server response ([number]^4 or original message)
responseLine = [Link]();
[Link]("Server: " + responseLine);
if ([Link]("QUIT") || responseLine == null) {
break;
}
}
} catch (UnknownHostException e) {
[Link]("Don't know about host " + SERVER_HOST);
} catch (IOException e) {
[Link]("Couldn't get I/O for the connection to " + SERVER_HOST + ": " +
e);
[Link]();
} finally {
try {
if (os != null) [Link]();
if (is != null) [Link]();
if (socketOfClient != null) [Link]();
} catch (IOException e) {
[Link]("Error closing resources: " + e);
}
}
}
}