为什么客户端和服务器不能同时写入通道?

时间:2020-03-15 07:21:32

标签: java sockets socketchannel

//server code
public class BlockingServer_WriteToSocket {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        ssChannel.bind(new InetSocketAddress(9898));
        FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);

        SocketChannel sChannel = ssChannel.accept();
        System.out.println("BlockingServer accept");
        ByteBuffer buf = ByteBuffer.allocate(1024);
        System.out.println("befor loop");
        int i = 1;
        while (inChannel.read(buf) != -1) {
            System.out.println("BlockingServer write to channel "+ i++ + " "+new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(new Date()));
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }
        System.out.println("already get data, and output to local file");

        sChannel.close();
        inChannel.close();
        ssChannel.close();
    }
}

//client code
public class BlockingClient_WriteToSocket {
    public static void main(String[] args) throws IOException {
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        FileChannel inChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ);

        ByteBuffer buf = ByteBuffer.allocate(1024);
        System.out.println("befor loop");
        int i = 1;
        while (inChannel.read(buf) != -1) {
            System.out.println("BlockingClient write to channel "+i++ + " "+new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(new Date()));
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }
        System.out.println("already get data, and output to local file");

        inChannel.close();
        sChannel.close();
    }
}

然后依次运行服务器和客户端。从打印结果中,您会发现服务器在最后一次写入通道之后,客户端开始第一次写入通道。但是为什么?

最后,由于服务器关闭了套接字,因此客户端报告了错误。

//server print
BlockingServer write to channel 52 2020/03/15-14:58:17:665
BlockingServer write to channel 53 2020/03/15-14:58:17:665
BlockingServer write to channel 54 2020/03/15-14:58:17:665
already get data, and output to local file

//client print
befor loop
BlockingClient write to channel 1 2020/03/15-14:58:17:670
BlockingClient write to channel 2 2020/03/15-14:58:17:671
Exception in thread "main" java.io.IOException: The software in your host terminated an established connection.

0 个答案:

没有答案