首页 > 解决方案 > c# NetworkStream.Read error 无法从传输连接中读取数据

问题描述

我正在构建一个由 c# 制成的套接字服务器。客户端每秒发送一次 ping 数据包。然后,服务器会定期向客户端发送 ping 数据包。当大约 20 台设备连接到服务器时,会在短时间内出现以下错误。

System.IO.IOException:无法从传输连接读取数据:A

连接尝试失败,因为连接方没有正确响应

一段时间后,或建立连接失败,因为连接的主机

没有回应。---> System.Net.Sockets.SocketException:一个连接

尝试失败,因为连接方在

一段时间,或建立连接失败,因为连接的主机有

没有回应

在 System.Net.Sockets.NetworkStream.Read(字节 [] 缓冲区,Int32 偏移量,Int32 大小)

--- 内部异常堆栈跟踪结束 ---

在 System.Net.Sockets.NetworkStream.Read(字节 [] 缓冲区,Int32 偏移量,Int32 大小)

在 System.IO.StreamReader.ReadBuffer()

在 System.IO.StreamReader.ReadLine()

发生该错误时,几乎所有连接的客户端套接字都会同时发生该错误。服务器套接字的ReceivedTimeout 和SendTimeout 由3 秒改为10 秒。但同样的方法有错误。

我一直在寻找这个问题的解决方案超过 3 天

它正在通过 asp.net 开发并通过 iis 分发。

void ReceiveRunnable()        
{

            log.Debug($"Start 'Receive Runnable'");
            try
            {

                int exceptionCount = 0;

                string line;

                while (IsRun)
                {
                    try
                    {
                        while (socket != null && (line = reader.ReadLine()) != null)
                        {
                            exceptionCount = 0;

                            if (!string.IsNullOrWhiteSpace(line))
                            {
                                // Ping Packet
                                if (line[0] == '0')
                                {
                                    ReceivePingPacket(line);
                                }
                                else
                                {
                                    buffer.Enqueue(line);
                                }
                            }
                        }
                    }
                    catch (SocketException e)
                    {
                        log.Error(e + "   e:" + e.SocketErrorCode);
                        break;
                    }
                    catch (IOException e)
                    {
                        if (IsRun)
                        {
                            log.Error(e);
                            break;
                            Thread.Sleep(100);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (IsRun)
                {
                    log.Error(e);
                }
            }
            finally
            {
                Close();
                OnDisconnect?.Invoke(this);
            }
            log.Debug($"Stop 'Receive Runnable'");
        }

标签: c#socketsnetworkstream

解决方案


推荐阅读