C#TCP侦听器崩溃
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#TCP侦听器崩溃相关的知识,希望对你有一定的参考价值。
多次发送消息(随机)时TCP侦听器崩溃,并抛出此异常,有任何解决方案可以修复它吗?
这是一个例外:
System.IO.IOException: Unable to read data from 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
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32
size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32
size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32
size)
这是我的TCP侦听器代码(标记了引发异常的错误行):
static string serverstatus = "0";
try
{
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i;
//THROW THE ERROR
while ((i = stream.Read(bytes, 0, bytes.Length)) > 0)
{
data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
if (data != "0" && data != serverstatus)
{
serverstatus = data;
Console.WriteLine("Current Status is: " + serverstatus);
}
data = serverstatus.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(serverstatus);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Server Sending Back: {0}", serverstatus);
}
}
}
catch (Exception _ex)
{
Console.WriteLine(_ex.ToString());
Console.ReadKey();
}
答案
.NET API通过您在此处遇到的异常公开已关闭或失败的连接。您需要处理异常(关闭流,清理事物等)并继续处理下一个客户端。
顺便说一下:
stream.Read(bytes, 0, bytes.Length)
不会完全读取bytes.Length
字节,但是在1和bytes.Length
字节之间的任何内容。如果您需要完全相同的字节数,则需要在循环中调用它。
如果serverStatus
不完全是bytes.Length
字节,那么协议也会遗漏一些成帧信息,因为客户端可能不知道在尝试将数据解码为消息之前尝试实际读取数据需要多长时间。
以上是关于C#TCP侦听器崩溃的主要内容,如果未能解决你的问题,请参考以下文章