c# - 使用相同的NetworkStream进行读写时,出现IOException

标签 c# sockets

我从以下代码获得IOExection

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

我该怎么做才能解决此问题?

RegisterHandle只是写数据然后读回;效果很好。但是,在SendMessage中写入时失败。

最佳答案

实际上,所有这些都在文档中进行了详细说明

您需要尝试检查异常消息,并且如果您对连接套接字有控制权,请找出它正在关闭的位置。如果以上都不是,则可能是网络问题,但我首先要进行Occam's razor分析

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.



备注

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.



注意

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.

关于c# - 使用相同的NetworkStream进行读写时,出现IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49091232/

相关文章:

java - 如何在邮件服务器上测试安全 SMTP 邮件服务

windows - WSAEventSelect,零事件

c# - 带参数启动线程

c# - 检查 IEnumerable<T> 是否不包含重复项(= 不同)的快速方法

swift - GCDAsyncUdpSocket 套接字在发送 255 个数据包之间关闭

python TCP套接字在recv方法上阻塞

PHP 和 C++ 发送/接收事件

C#:实现格式良好的时间字符串的最佳方法?

c# - 从 powershell 调用 api 时,空值来自 Post 方法(FromBody)

java - 图像导出 DayPilot 调度程序