简体   繁体   中英

IOException when reading and writing with same NetworkStream

I get an IOExection from the following code

public async Task Register(string handle)
{
    // send register handle
    using (NetworkStream stream = client.GetStream())
    {
        await RegisterHandle(stream);
        var line = "hello world";
        await SendMessage(stream, line);
    }
}

public async Task SendMessage(NetworkStream stream, string message)
{
    Console.WriteLine("SendMessage(" + message + ")");
    await Async.Write(stream, message);
    Console.WriteLine("End of SendMessage");
}

System.AggregateException: One or more errors occurred. (Unable to transfer    data on the transport connection: An established connection was aborted by the software in your host machine.) ---> System.IO.IOException: Unable to transfer data on the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine

What can I do to fix this?

RegisterHandle just writes data then reads back; which works fine. However it fails when writing inside SendMessage.

Its actually all explained in detail in the docuemtnation

You need to try and check the exception messages, and if you have control over the connecting socket work out what it is closing on you. If none of the above you may have a network problem but i would go with the Occam's razor analysis first

NetworkStream.Write Method (Byte[], Int32, Int32)

IOException There was a failure while writing to the network.

-or-

An error occurred when accessing the socket. See the Remarks section for more information.

Remarks

The Write method starts at the specified offset and sends size bytes from the contents of buffer to the network. The Write method blocks until the requested number of bytes is sent or a SocketException is thrown. If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code, and refer to the Windows Sockets version 2 API error code documentation in MSDN for a detailed description of the error.

Note

Check to see if the NetworkStream is writable by accessing the CanWrite property. If you attempt to write to a NetworkStream that is not writable, you will get an IOException. If you receive an IOException, check the InnerException property to determine if it was caused by a SocketException.

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