TCP协议的简单应用一
TCP协议的应用,实现一个服务器处理多个客户端请求(向服务器发送消息,服务器接收到后以原消息返回给客户端。)
客户端类
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
//先写出后读入
public class EchoMultiClient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
//创建一个Socket对象,指定要连接的服务器
Socket socket = new Socket("127.0.0.1",6666);
//向服务器发送数据,先从socket获得输出流,并包装
PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
System.out.println("请输入要发送的内容:");
String info = input.nextLine();
ps.println(info);
ps.flush();
//读取服务器返回的消息,先从socket获得输入流,并包装
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
info = br.readLine();
System.out.println(info);
//关闭流
br.close();
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器类
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 处理多个客户端
* 主线程用于监听客户端的连接,每次有链接成功,开启一个线程来该客户端的消息
*/
public class EchoMultiServer {
public static void main(String[] args) {
//创建一个固定大小的线程池
ExecutorService es = Executors.newFixedThreadPool(3);
try {
//创建服务器端套接字,并指定端口号
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器已启动,等待连接。。");
//现在不直接处理了,主线程只负责接待,具体操作交由其他线程实现
while (true) {
Socket socket = serverSocket.accept();
System.out.println("一个客户端连接成功。。。" + socket.getInetAddress().getHostAddress());
es.execute(new UserThread(socket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 用来处理客户端请求的线程任务
*/
class UserThread implements Runnable {
//处理谁?
private Socket socket;
public UserThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
//读取客户端请求
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String info = br.readLine();
System.out.println(info);
//向客户端返回消息
PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
ps.println("echo:" + info);
ps.flush();
ps.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}