简体   繁体   中英

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? At around the 60k byte mark the values stay all zeros. I admit I haven't worked much with Streams or TCP so I'm sure I've done something wrong; I just don't understanding what it is. I've tried this with both InputStream and BufferedInputStream on the server with the same result. 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:

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
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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