server服务端(使用线程池,减少线程创建销毁的消耗)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TcpEchoThreadServer {
private ServerSocket serverSocket = null;
public TcpEchoThreadServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void start() throws IOException {
System.out.println("服务器启动");
//先创建一个线程池实例
ExecutorService executorService = Executors.newCachedThreadPool();
while(true){
//针对这个连接,单独创建一个线程负责处理
Socket clientSocket = serverSocket.accept();
executorService.execute(new Runnable() {
@Override
public void run() {
processConnection(clientSocket);
}
});
}
}
public void processConnection(Socket clientSocket){
System.out.printf("[%s:%d] 客户端上线!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))){
while(true){
//1.读取请求并解析
String request = bufferedReader.readLine();
//2.根据请求计算响应
String response = process(request);
//3.把响应写回到客户端
bufferedWriter.write(response+"\n");
bufferedWriter.flush();
System.out.printf("[%s:%d] rep: %s;resp: %s\n",clientSocket.getInetAddress().toString(),
clientSocket.getPort(),request,response);
}
}catch(IOException e){
//e.printStackTrace();
System.out.printf("[%s:%d] 客户端下线!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
}
}
private String process(String request) {
return request;
}
public static void main(String[] args) throws IOException {
TcpEchoThreadServer server = new TcpEchoThreadServer(9090);
server.start();
}
}
client服务端:
1.启动客户端(不绑定端口号)和服务器建立连接
2.进入主循环
a)读取用户输入内容
b)构造一个请求发送给服务器
c)读取服务器的响应数据
d)把响应数据显示到界面上
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class TcpEchoClient {
private Socket socket = null;
public TcpEchoClient(String serverIp,int serverPort) throws IOException {
//此处的实例化Socket过程,就是在建立TCP连接
socket = new Socket(serverIp,serverPort);
}
public void start() {
System.out.println("客户端启动");
Scanner scanner = new Scanner(System.in);
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
while (true) {
//读取用户输入内容
System.out.println("->");
String request = scanner.nextLine();
if ("exit".equals(request)) {
break;
}
//构造请求并发送给服务器,此处用 \n 是为了和服务器中的readLine相对应
bufferedWriter.write(request + "\n");
bufferedWriter.flush();
//读取服务器的响应数据
String response = bufferedReader.readLine();
//把响应数据显示到界面上
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
client.start();
}
}