Câu 1: Thiết kế một Server phục vụ ở chế độ tuần tự có nối kết. Trong đó:
+ Server làm nhiệm vụ kiểm tra dữ liệu nhận từ client có phải số
hay không và thông báo cho client biết khi không hợp lệ.
Nếu n là số thì tính tổng tất cả số chẵn trong khoảng từ 0 – n.
+ Client sẽ nhập 1 số nguyên dương n, gửi qua Server,
nhận kết quả trả về từ Server và thể hiện lên màn hình.
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package kiemthu;
import java.net.*;
import java.io.*;
/**
*
* @author PTVLNE
*/
public class server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
ServerSocket ss = new ServerSocket(7);
System.out.println("Da tao server");
while (true) {
Socket s = ss.accept();
System.out.println("co 1 client ket noi" + s.getInetAddress().getHostAddress());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
try {
int n = dis.readInt();
if (n>=0){
int sum = 0;
for(int i = 0; i<=n;i+=2){
sum +=i;
}
dos.writeInt(sum);
}else{
dos.writeUTF("vui long nhap lai so");
}
} catch (IOException e) {
System.out.println("xay ra loi "+e.getMessage());
} finally{
s.close();
System.out.println("dong ket noi");
}
}
} catch (IOException e) {
System.out.println("Xay ra loi");
}
}
}