.net c#套接字编程中读取数据错误

error of reading data in socket programming
2021-03-07
  •  译文(汉语)
  •  原文(英语)

我写了一个控制台应用程序.我使用套接字编程.我在鳕鱼下面得到错误.数据传输速度为10ms.一段时间后,我在"while((i = stream.Read(bytes,0,bytes.Length))!= 0)"行上收到错误.

while (true)
{
    TcpClient tcpClient = tcpListener.AcceptTcpClient();
    NetworkStream stream = tcpClient.GetStream();

    String data = null;
    int i;
    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
    {
        // Translate data bytes to a ASCII string.
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
        Console.WriteLine("Received: {0}", data);
       ...
    }

错误:

System.dll中发生了类型为'System.IO.IOException'的未处理异常.其他信息:无法从传输连接中读取数据:连接尝试失败,因为经过一段时间或建立的连接,被连接方未正确响应失败,因为连接的主机无法响应.

速聊1:
当服务器用事件或类似事件响应您时,您不需要等待吗?我认为,您的问题是您正在尝试读取空流.
速聊2:
我每10毫秒从clinet获取数据.我可以使用什么活动?
解决过程1

当您做IO或网络工作时,您的代码需要能够处理特殊情况,例如,使用套接字,服务器突然关闭其连接端,您的代码就必须能够处理该情况.而且您的代码对该异常没有任何作用.

为此,您需要将代码放入try / catch块中

try
{
    // put socket code stuff here
}
catch(IOException ioe)
{
    // put excpetion code here.
}

希望这可以帮助.

i wrote a console application. i used socket programming . i get error in below cod. transfer speed of data is 10ms . after a period of time i get a error on " while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)" line .

while (true)
{
    TcpClient tcpClient = tcpListener.AcceptTcpClient();
    NetworkStream stream = tcpClient.GetStream();

    String data = null;
    int i;
    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
    {
        // Translate data bytes to a ASCII string.
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
        Console.WriteLine("Received: {0}", data);
       ...
    }

error :

An unhandled exception of type 'System.IO.IOException' occurred in System.dll Additional information: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Talk1:
Don't you need to wait when the server responds you with an event or something like it? I think, you problem is that you are trying to read an empty stream.
Talk2:
i get data from clinet on every 10 ms. what event i can use?
Solutions1

When you do IO stuff or network stuff, your code needs to be able to handle excpetional circumstances, so say with a socket, the server suddenly shuts down their end of a connection, your code needs to be able to handle that. And your code isn't doing anything with that exception.

To do this you need to put your code in a try/catch block

try
{
    // put socket code stuff here
}
catch(IOException ioe)
{
    // put excpetion code here.
}

Hope this helps.

转载于:https://stackoverflow.com/questions/23028272/error-of-reading-data-in-socket-programming

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入