简体   繁体   English

从Java中的套接字读取字节

[英]Read bytes from socket in Java

I have a Socket in Java ( java.net.ServerSocket ). 我有一个Java套接字( java.net.ServerSocket )。 I read from it using InputStream . 我使用InputStream读取它。

I would like to read several bytes from socket, when they are available. 我想从套接字读取几个字节,当它们可用时。 So I use InputStream.read(bytes, 0, num) . 所以我使用InputStream.read(bytes, 0, num)

It works fine when I test it locally (over 127.0.0.1). 我在本地测试它(127.0.0.1以上)时工作正常。 But when I put it on internet and connect to it, it reads only 2916 bytes. 但是,当我把它放在互联网上并连接到它时,它只读取2916字节。 How can I read exactly "num" bytes and don't continue, unitl I receive them? 如何准确读取“num”字节并且不继续,我收到它们?

Sounds like something to do with the way your network is set up. 听起来与您的网络设置方式有关。 Something else could be sending data to it. 还有其他东西可以向它发送数据。 Have you tried using a different port? 您尝试过使用其他端口吗?

If that doesn't work, try disabling your network connection / disconnecting from your network to see if its something from outside which is actually causing the problem. 如果这不起作用,请尝试禁用网络连接/断开与网络的连接,以查看外部是否存在实际导致问题的内容。

That is the way how readings of sockets usually works. 这就是套接字读数通常如何工作的方式。 When using slower 'network' than loopback, all data is not transferred immediately. 使用较慢的“网络”而不是环回时,不会立即传输所有数据。

read(bytes, 0, num) will return when there is data available. 当有可用数据时read(bytes, 0, num)将返回。 There may be one or more bytes, even more than num bytes available. 可能有一个或多个字节,甚至超过可用的num个字节。 num only limits how much data is moved to bytes array. num仅限制将数据移动到bytes数组的数量。

So if you want to receive excatly num bytes, then you must call read again. 因此,如果您想要接收令人兴奋的num字节,那么您必须再次调用read Of cource with smaller len and bigger off parameters. 具有较小len和较大off参数的cource。

Example: 例:

    int offset = 0;
    int wanted = buffer.length;

    while( wanted > 0 )
    {
        final int len = istream.read( buffer, offset, wanted );     
        if( len == -1 )
        {
            throw new java.io.EOFException( "Connection closed gracefully by peer" );
        }
        wanted -= len;
        offset += len;
    }

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

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