简体   繁体   English

有人请解释为什么我无法通过TCP将大字节[]发送到服务器

[英]Someone please explain why I'm having trouble sending large byte[] to server via TCP

Can someone please explain to me why byte[] buf on the server does not contain 100,000 1s as sent by the client? 有人可以向我解释为什么服务器上的byte[] buf不包含客户端发送的100,000个1吗? At around the 60k byte mark the values stay all zeros. 在大约60k字节标记处,值保持全零。 I admit I haven't worked much with Streams or TCP so I'm sure I've done something wrong; 我承认我在Streams或TCP方面工作不多,所以我确定我做错了什么。 I just don't understanding what it is. 我只是不明白那是什么。 I've tried this with both InputStream and BufferedInputStream on the server with the same result. 我已经在服务器上使用InputStreamBufferedInputStream尝试了相同的结果。 Thank you to anyone/everyone who can take the time to explain this to me! 谢谢任何能抽出宝贵时间向我解释的人!

Client code is pretty simple: 客户端代码非常简单:

    byte[] msgBytes = new byte[100000];
    for (int i=0;i<msgBytes.length;i++){
        msgBytes[i] = 1;
    }
    Socket sck = null;
    try {
        sck = new Socket("my.server.net", 1234);
        OutputStream outStream = sck.getOutputStream();
        outStream.write(msgBytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            sck.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Likewise, server code is also simple: 同样,服务器代码也很简单:

    ServerSocket srvSock = new ServerSocket(1234);
    Socket sock = srvSock.accept();
    returnAddress = sock.getInetAddress();
    returnPort = sock.getPort();
    BufferedInputStream iStream = new BufferedInputStream(sock.getInputStream(), 100000);
    byte[] buf = new byte[100000];
    iStream.read(buf);

Try substituting BufferedInputStream with DataInputStream and use readFully , so your server code should became: 尝试用DataInputStream代替BufferedInputStream并使用readFully ,因此您的服务器代码readFully为:

ServerSocket srvSock = new ServerSocket(1234);
Socket sock = srvSock.accept();
returnAddress = sock.getInetAddress();
returnPort = sock.getPort();
DataInputStream iStream = new DataInputStream(sock.getInputStream());
byte[] buf = new byte[100000];
iStream.readFully(buf);

Yes but anyway you need to read all the stream, you don't know size on other side. 是的,但是无论如何,您都需要阅读所有流,您不知道另一边的大小。 Moreover you should not read stream content to memory but better try to procces it. 此外,您不应将流内容读取到内存中,而最好尝试进行处理。

BufferedInputStream iStream = new BufferedInputStream(sock.getInputStream(), 100000);
 byte[] buf = new byte[100000];
 int cnt;
 StringBuffer content = new StringBuffer();
 while ((cnt = iStream.read(buf)) != -1) {
   content.append(buf); // you should not store content of stream, but better process it if possible
 };

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

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