java网络编程之服务器同时处理多个客户端示例
程序员文章站
2024-03-22 19:04:34
...
服务器端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 处理多个客户端
* 主线程用于监听客户端的连接,每次连接成功,开启一个线程来处理该客户端的消息
*/
public class MutilServerDemo {
public static void main(String[] args) {
ExecutorService es= Executors.newFixedThreadPool(3);//用线程池处理
try {
ServerSocket server=new ServerSocket(6666);
System.out.println("服务器已经启动,正在等待链接...");
while(true){
Socket s=server.accept();
System.out.println(s.getInetAddress().getHostAddress());
es.execute(new UserThread(s));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 用来处理客户端请求的
*/
class UserThread implements Runnable{
private Socket s;
public UserThread(){}
public UserThread(Socket s){
this.s=s;
}
@Override
public void run() {
try {
BufferedReader br =new BufferedReader(new InputStreamReader((s.getInputStream())));
PrintStream ps=new PrintStream(new BufferedOutputStream(s.getOutputStream()));
String info =br.readLine();
System.out.println(info);
ps.println("echo:"+info);
ps.flush();//刷新
ps.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class MutilClientDemo {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
//创建一个Socket,指定要连接的服务器
try {
Socket socket=new Socket("localhost",6666);//执行成功,这Echo
//获取socket的输入和输出流
PrintStream ps=new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("请输入:");
String info=input.nextLine();
ps.println(info);
ps.flush();
//读取服务器端返回的数据
info=br.readLine();
System.out.println(info);
ps.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}