DCâu 2: Thiết kế một Server phục vụ ở chế độ song song có nối kết. Trong đó:
+ Server làm nhiệm vụ kiểm tra xem ký tự a có xuất hiện trong chuỗi hay không.
+ Client sẽ nhập vào một chuỗi, gửi qua Server, nhận kết quả trả về từ Server
và thể hiện lên màn hình là “Có” hay “Không”.
/*
* 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_cau2;
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 sever");
while (true) {
Socket s = ss.accept();
System.out.println("Co 1 client ket noi"+ s.getInetAddress().getHostAddress());
new Thread(new Client(s)).start();
}
} catch (IOException e) {
System.out.println("Loi ket noi den server " + e.getMessage());
}
}
}
class Client implements Runnable{
private final Socket client;
public Client(Socket client){
this.client = client;
}
@Override
public void run(){
try {
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
try{
String str = dis.readUTF();
boolean bl = str.contains("a");
dos.writeBoolean(bl);
}catch (IOException e){
System.out.println("Loi du lieu "+e.getMessage());
}finally{
client.close();
System.out.println("dong ket noi");
}
} catch (IOException e) {
System.out.println("Khong the ket noi may chu"+ e.getMessage());
}
}
}