开发者

Socket closing with error

I'm writing a bunch of data to a socket, however, after what seems like around 64k is written the socket is closed with an error "Connection reset by peer". I believe what is happening is that what is reading the socket (Android media player) is dying when trying to read more data than is available from the socket. This is a song that is being streamed and when the id3 tag is fairly large, it fails. However, when I remove the id3 information from the song, it works fine.

Since I believe that the reading side is failing when there is not enough data, I am wondering if it is possible to write a bunch of data to the socket before calling socket.accept() to accept the connection to read it. My thinking here is that when the media player connects to the socket that there will be enough data for it to read and therefore not crash. So can you call the write() before accept()?

Here's some psudocode of my current code:

    ServerSocket socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));

    socket.setSoTimeout(10000);
    port = socket.getLocalPort();

    Socket client = socket.accept();

    ...

    while (isRunning && (readBytes = data开发者_运维问答.read(buff, 0, buff.length)) != -1) {

        client.getOutputStream().write(buff, 0, readBytes);           

    }


This usually means you have written to a connection that has already been closed by the other end. In other words, an application protocol error. The 64k probably just represents the amount of buffering between you and the peer.

Your question about writing to the socket before accept() doesn't make sense if it refers to the server. However if you mean the client writing to the socket, that can indeed happen. The client can connect, write (up to the limit of the available buffering) and close before the server ever calls accept. This is due to the TCP 'backlog' queue whereby the TCP stack completes connections aysnchronously and queues them, ready to be accepted by the application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜