ServerSocket服务端和Socket客户端

public class ServerTcp {

    public static void main(String[] args) throws IOException {
        int port = 6666; // 选择一个端口号
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server started. Listening on port " + port);

        try {
            while (true) {
                // 无限循环,等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("New client connected: " + clientSocket.getInetAddress());

                // 创建一个新线程来处理请求
                Thread clientHandler = new Thread(new ClientHandler(clientSocket));
                clientHandler.start();
            }
        } finally {
            serverSocket.close(); // 关闭ServerSocket
        }
    }


}
public class ClientHandler implements Runnable {
    private Socket clientSocket;

    public ClientHandler(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = clientSocket.getInputStream();
            byte[] buff = new byte[1024];
            int len;

            len = inputStream.read(buff);
            System.out.println(new String(buff, 0, len));
            OutputStream os = clientSocket.getOutputStream();
            os.write((UUID.randomUUID().toString()+"服务端返回信息").getBytes());

            os.close();
            inputStream.close();

        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ClientTcp {
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("localhost",6666);
        OutputStream outputStream = client.getOutputStream();
        outputStream.write("客户端请求信息".getBytes());
        InputStream is = client.getInputStream();

        byte[] buff = new byte[1024];
        int len;
//        while ((len = is.read(buff)) != -1){
//            System.out.println(new String(buff,0,len));
//        }
        len = is.read(buff);
        System.out.println(new String(buff,0,len));


        is.close();
        outputStream.close();
        client.close();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值