简体   繁体   English

Java套接字:读取不返回

[英]Java socket: Read does not return

It was supposed to be a 5-minutes test just to see whether it works as suggested. 为了查看它是否如建议的那样,应该进行5分钟的测试。 I wanted to create a stupidly simple HTTP "server" that does nothing but printing out what it gets (namely the HTTP requests). 我想创建一个愚蠢的简单HTTP“服务器”,除了打印输出内容(即HTTP请求)外,什么也不做。

public static void main(String args[]) throws IOException {
    ServerSocket server = new ServerSocket(port); 
    try (Socket socket = server.accept()) {
        DataInputStream input = new DataInputStream(socket.getInputStream());
        String received = input.readUTF();
        System.out.println("Received: \n" + received);
    }
}

But I came up with the following problem: When I start his program and then try http://localhost/ in Firefox, the stream gets stuck in the readUTF() method. 但是我想到了以下问题:当我启动他的程序,然后在Firefox中尝试http:// localhost /时,流卡在了readUTF()方法中。 It simply does not return. 它根本不会返回。

I tried the same with socket channels and a buffer size of 128. There, it gets stuck after the third read (so anywhere between the 384th and 511th byte). 我用套接字通道和128的缓冲区大小尝试了相同的操作。在那里,它在第三次读取后卡住了(因此在第384个字节与第511个字节之间的任何位置)。 This is the following code: 这是下面的代码:

public static void main(String args[]) throws IOException {
    CharsetDecoder decoder = Charset.forName("UTF8").newDecoder();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(port)); 
        ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
        buffer.clear();
        SocketChannel socketChannel = serverSocketChannel.accept(); 
        StringBuilder received = new StringBuilder();
        while (socketChannel.read(buffer) > 0) {
            buffer.position(0);
            received.append(decoder.decode(buffer).toString()); 
            buffer.clear();
        }
        System.out.println("Received: \n" + received.toString());
    }

They both show the same behaviour that the read method does not terminate. 它们都表现出与read方法不会终止相同的行为。 Do you have any idea, how to solve this and especially, what is the reason for this behaviour? 您有任何想法,如何解决这个问题,尤其是这种行为的原因是什么?

DataInputStream is used to read binary data. DataInputStream用于读取二进制数据。 In this particular case it means that readUTF() method reads first the string length as two bytes and then reads as many bytes as the length received. 在这种特殊情况下,这意味着readUTF()方法首先将字符串长度读取为两个字节,然后读取与接收到的长度一样多的字节。

This stream is not usable for your needs, just simply read from getInputStream() or wrap it with BufferedReader . 此流无法满足您的需求,只需从getInputStream()读取或将其包装为BufferedReader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM