Java中的Socket流程及简单实现

本文介绍了Java中使用ServerSocket和Socket进行网络通信的基本流程,包括服务端和客户端的创建,以及字节数组数据交换的过程。示例代码展示了如何实现简单的Socket通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在java中基于socket的网络通信主要是使用ServerSocket及Socket来分别构建服务端和客户端,双方通过发送和接收字节数组来实现数据的交换,其通信流程如下:

 示例代码如下:

服务端Server.java

public class Server {

    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("server started...");
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("client connected...");
            executorService.execute(() -> {
                process(socket);
            });
        }
    }

    public static void process(Socket socket) {
        long threadId = Thread.currentThread().getId();
        String threadName = Thread.currentThread().getName();
        System.out.println("thread id:" + threadId + ", thread name:" + threadName);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            System.out.println("client:" + new String(bytes, 0, read));

            outputStream = socket.getOutputStream();
            outputStream.write("hello client".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

客户端Client.java

public class Client {

    public static void main(String[] args) throws IOException {
        while (true) {
            Socket socket = new Socket("127.0.0.1", 9999);
            OutputStream outputStream = socket.getOutputStream();
            System.out.println("Please input string:");
            Scanner scanner = new Scanner(System.in);
            String msg = scanner.nextLine();
            outputStream.write(msg.getBytes());

            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            System.out.println("Message from server:" + new String(bytes, 0, read).trim());
            socket.close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值