4、服务器与多客户端通信
目前为止我们编写的程序中,服务器只能同时处理一个客户端连接,要想服务器同时支持多个客户端的连接,就必须加入多线程的处理机制,将每一个连接的客户端都创建一个新的线程对象。
服务器端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
处理多个客户端
主线程用于监听客户端的连接,每次有连接成功,开启一个线程来处理该客户端的消息
*/
public class MutiServerDome {
public static void main(String[] args) {
//线程池:4条
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 UerThread(s));
}
}catch (IOException e){
e.printStackTrace();
}
}
}
/*
用来处理客户端请求的线程任务
*/
class UerThread implements Runnable{
private Socket s;
public UerThread(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 MutiClientDemo {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
try {
//创建一个socket对象,指定要连接的服务器
Socket socket=new Socket("localhost",6666);
//获取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();
}
}
}
服务器已启动,等待连接······
127.0.0.1
one
127.0.0.1
tow
127.0.0.1
three
服务器通过加入多线程池来处理多个客户端请求,简单的设置线程数可以与CPU核数匹配,过多的线程数空闲会消耗服务器资源