简体   繁体   中英

Java client socket using writeBytes

I'm reading a string from a buffer and writing it to a server. The problem I'm having is that the string never gets received by the server when I leave the socket open and write in a loop. When I use this:

    try {       
        Socket send = new Socket("localhost", 1490);
        DataOutputStream out = new DataOutputStream(send.getOutputStream());
        String message = null;
        while ((message = buffer.get()) != null){
            out.writeBytes(message);
        }
        out.close();
        send.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

the server doesn't receive the string, but when I do this it works properly:

    try {       

        String message = null;
        while ((message = buffer.get()) != null){
            Socket send = new Socket("localhost", 1490);
            DataOutputStream out = new DataOutputStream(send.getOutputStream());
                    out.writeBytes(message);
            out.close();
            send.close();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Obviously I don't want to keep opening and closing the socket, though. What is the problem?

You need to flush your socket every time you want to send a data packet. Closing a socket forces an automatic flush and that explains why your data is getting sent on socket close.

The data is not being written to the socket even when you close it? (in your first snippet that is)

Also, have you tried to use the flush method? You can read about it here: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/DataOutputStream.html#flush () and your code will look like:

try {       
    Socket send = new Socket("localhost", 1490);
    DataOutputStream out = new DataOutputStream(send.getOutputStream());
    String message = null;
    while ((message = buffer.get()) != null){
        out.writeBytes(message);
        out.flush();
    }
    out.close();
    send.close();
} catch (IOException ex) {
    ex.printStackTrace();
}

Let me make a guess.

Does the buffer.get() method block? If so, then the problem is that out.writeBytes(message) does not guarantee that the entire byte representation to be pushed to the server. Instead. there is a good chance that your client has buffered bytes waiting to be flushed through to the server.

If this is what is going on, then calling flush after each call to writeBytes will fix the problem.

But if the buffer.get() method doesn't block, then calling flush won't make any difference. In fact, it will just increase the network traffic. So adding the flush "just in case" is a bad idea.


Another possibility is that there is something wrong with the server-side code.

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