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

Java TCP Client-Server BigInteger Example

The document describes two programming assignments involving TCP socket communication between a client and server in Java. The first assignment requires the server to calculate the fourth power of an integer received from the client, while the second assignment involves the server calculating four times a student's ID and handling messages from the client, including positive integers and other messages. Both assignments include detailed code implementations for the server and client, demonstrating the use of threads and input/output streams.

Uploaded by

Thùy Ngân Phan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Java TCP Client-Server BigInteger Example

The document describes two programming assignments involving TCP socket communication between a client and server in Java. The first assignment requires the server to calculate the fourth power of an integer received from the client, while the second assignment involves the server calculating four times a student's ID and handling messages from the client, including positive integers and other messages. Both assignments include detailed code implementations for the server and client, demonstrating the use of threads and input/output streams.

Uploaded by

Thùy Ngân Phan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ĐỀ 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);
}
}
}
}

Common questions

Powered by AI

Error handling in the client-server communication processes is implemented through several strategies. First, exceptions like IOException and EOFException are caught to handle communication errors gracefully. The server logs errors and continues running, ensuring clients can connect without crashing the server. The client checks for NumberFormatException to validate user input, ensuring only valid integers are processed. In cases of input/output errors or invalid message formats, the system provides feedback to the user, maintaining robustness and stability in the communication process .

TCP Sockets are significant in network programming due to their reliable delivery and connection-oriented nature, which ensures data integrity and sequence. Unlike UDP, which is faster but lacks reliability, TCP guarantees that data packets will be delivered in order and without duplication, making it crucial for applications requiring precise and consistent data exchange, such as banking systems or multiplayer gaming. In the described client-server programs, this reliability ensures that complex numerical calculations are accurately sent and received without error, which is critical for maintaining consistency and correctness in mathematical operations .

Using a thread for each client affects the server's performance and scalability positively by allowing simultaneous processing of multiple client requests. This leads to better resource utilization and responsiveness as each client's operations are handled independently. However, this approach can also be a limitation at scale, as the number of threads can grow large, potentially overwhelming the server's processing and memory resources. This limits the server's scalability if not properly managed or if thread management is not optimized, making it crucial to consider alternatives like a thread pool or asynchronous I/O for large-scale applications .

Creating a multi-threaded server poses several challenges, including thread synchronization issues, resource sharing conflicts, and increased complexity in code management. Each thread operates independently, requiring careful handling of shared resources to avoid race conditions and deadlocks. Furthermore, the overhead of creating a new thread for each client may affect performance and memory usage, potentially leading to scalability issues as the number of clients increases. Additionally, debugging and maintaining a multi-threaded application can be more complex due to the non-linear execution of threads .

The use of `BufferedReader` and `BufferedWriter` enhances input/output operations in the client-server applications by providing efficient reading and writing of character streams. They reduce the frequency of I/O operations by buffering input and output, which minimizes the performance cost associated with direct reads and writes to streams. This buffering is particularly beneficial in network applications where there are multiple small I/O operations. It allows for improved performance and reduced latency, as data can be collected in a buffer and written or read in bulk, enhancing overall efficiency in communications .

When the server receives a client's message that is a positive integer, it calculates the fourth power of this number using BigInteger's `pow` method, which accurately computes large power calculations beyond the typical range of primitive data types. This result is then sent back to the client as a string. If the client's message is not a positive integer, the server simply returns the original message. This approach not only ensures accurate calculations but also maintains efficient communication of results .

The implementation of TCP socket communication enhances the functionality of the client-server program by providing a reliable, ordered, and error-checked delivery of data between the client and server. In the programs described, the server listens on a specific port to accept client connections and creates threads to handle each client independently, enabling concurrent processing. This setup allows the server to perform computations, specifically calculating the fourth power of numbers and communicating results back to the clients efficiently .

The client program handles the termination of the connection with the server by monitoring user input for a specific termination keyword, such as "QUIT." When this keyword is detected or the connection from the server is closed, the client initiates a clean shutdown process. This includes closing the input/output streams and the socket connection, releasing any resources used during the session. This orderly shutdown ensures that there are no resource leaks and that both client and server can properly terminate the session without errors .

Threading plays a crucial role in managing multiple client connections by allowing the server to handle each client in a separate thread. This allows the server to maintain concurrent sessions with several clients simultaneously, without blocking other connections. Each thread handles receiving input, processing requests (such as computing n^4), and sending responses back to the client independently. This is essential for scalability and performance in a networked environment, as it prevents any single client from monopolizing the server's resources .

Using BigInteger provides significant advantages, particularly when dealing with large numeric values that exceed the capacity of standard integer types. In the computing scenarios described, BigInteger enables handling large computations like calculating n^4 without overflow issues typical in primitive data types. This is crucial for ensuring accurate results in applications where high precision in mathematical computations is required, such as the mathematics server that processes large values .

You might also like