那些年可以封神的代码:1,TCP Socket 通信

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) {
        try {
            //连接
            ServerSocket serverSocket = new ServerSocket(5555);
            System.out.println("服务器启动,等待客户端连接...");

            //阻塞
            Socket socket = serverSocket.accept();
            System.out.println("客户端已连接.");

            //创建 输入流。读取
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //创建 输出流。写入
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            String message = in.readLine();
            System.out.println("收到客户端消息:" + message);
            // 解析 JSON 消息

            // 发送响应给客户端
            out.println("构建响应 JSON");

            // 关闭连接
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TcpClient {
    public static void main(String[] args) {
        try {
            //指定服务端的地址
            Socket socket = new Socket("localhost", 5555);
            //创建 输出流 PrintWriter。发送数据
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            //创建 输入流 ,接收数据
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out.println("发送 JSON 消息给服务器");

            // 接收服务器的响应
            String response = in.readLine();
            System.out.println("服务器响应:" + response);

            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java,SE,tcp/ip,网络协议,socket)