这里我们简单写一个回显服务器当做 来解读流套接字编程用到的方法和逻辑, ServletSocket 是创建 TCP 服务端 Socket 的 API, 主要处理客户端的连接, Socket 主要用来和客户端进行具体的交互, 这里还需要注意 TCP 协议有连接, 类似于打电话; 此处我们实现的是一个长连接版本的服务器, 关于长连接和短连接的区别, 后面会解释.
服务端代码如下:
public class TcpEchoServer {
private ServerSocket serverSocket = null;
public TcpEchoServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void star() throws IOException {
System.out.println("服务器启动啦!");
while (true) {
Socket clientSocket = serverSocket.accept();
processConnection(clientSocket);
}
}
private 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) {
String request = bufferedReader.readLine();
bufferedWriter.write(reponse + "\n");
bufferedWriter.flush();
System.out.printf("[%s:%d] req: %s; resp: %s\n",clientSocket.getInetAddress().toString(),
clientSocket.getPort(), request,reponse);
}
} catch (IOException e) {
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 {
TcpEchoServer server = new TcpEchoServer(9090);
server.star();
}
}
public class TcpEchoClient {
private Socket socket = null;
public TcpEchoClient (String serverIp, int serverPort) throws IOException {
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;
}
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();
}
}