java实现TCP服务器

时间:2024-03-30 21:30:52
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
public class SimpleTCPServer {
    public static void main(String[] args) throws IOException {
        int port = 12345; // 选择一个端口号
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器启动,正在监听端口: " + port);
 
        while (true) {
            // 监听并接受连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("连接来自: " + clientSocket.getInetAddress().getHostAddress());
 
            // 处理请求
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String str = in.readLine();
            System.out.println("收到信息: " + str);
 
            // 关闭socket
            clientSocket.close();
        }
    }
}