简体   繁体   中英

Socket OutputStream::write method mixes TCP packets?

i have some problem with java socket.

I create simple proxy server which listen http request, transfer this request to source, and then return response, without disconnect. And sometimes client receive invalid data. I looked at tcp dump logs, and i found thet tcp packets was mixes

This is very simple code example

Socket socket = new Socket("127.0.0.1", 3000);

OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();

while (true) {
    final Request request = Request.read(in);
    if (request == null) return;

    try {
        // send http request 
        HttpRequest httpRequest = HttpRequest.factory(request);
        Response response = httpRequest.response();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        buffer.write(response.headers.toString());
        buffer.write(response.body);

        out.write(buffer.toByteArray());
        out.flush();
    } catch (ParserException | IOException e) {
        e.printStackTrace();
        return;
    }
}

This is a screen tcp dump log, which you can see 3 http response in one tcp packet http://dl2.joxi.net/drive/0009/2601/629289/150827/004858080b.jpg

Why is this happening, and how to solve this problem ?

Update 28.10.2015 17:50

Sorry guys, it was my fault on the server side. Java worked perfectly

What you're seeing is the expected, correct behavior. The Connection: keep-alive header means that the connection is kept open so that it can be used for more than one HTTP request. If it's combined with pipelining, the responses may even come in a single TCP segment.

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