服务器端
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);
try {
Socket socket=new Socket("localhost",6666);
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();
}
}
}