服务端
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){ //用一个循环,去循环的接收客户端发送过来的请求,每一个客户端的请求就new一个线程
Socket s = server.accept(); //等待客户端的连接,有一个连接就执行下面的new一个线程任务,所以当有多个客户端连接时就有多个线程
System.out.println(s.getInetAddress().getHostAddress());
es.execute(new UserRunnable(s));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 创建自定义线程,用来处理客户端请求的线程任务
*/
class UserRunnable implements Runnable{
private Socket s;
public UserRunnable(Socket s){
this.s=s;
}
@Override
public void run() {
try {
//读取客户端发送过来的消息
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String info= br.readLine();
System.out.println(info);
//消息重新发送(写入)到客户端
PrintWriter pw = new PrintWriter(new BufferedOutputStream(s.getOutputStream()));
pw.println("echo:"+info);
pw.flush();
pw.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);
try {
Socket socket = new Socket("localhost",6666);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
System.out.println("请输入...");
String in=input.nextLine();
pw.println(in);
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String info=br.readLine();
System.out.println(info);
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}