C# System.Net.Sockets.SocketException 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败

lijiazhicool 2012-03-08 08:05:04
我的C# udp通信协议有时候运行正常,有时候出现问题,不知道是什么情况,具体代码如下:

private static void RecieveData()
{
byte[] CmdStart_02 = new byte[8] { 0x12, 0x34, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00 };
byte[] CmdSetBias = new byte[8] { 0x12, 0x34, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00 };

byte[] data = new byte[1024];
// string input, stringData;
//构建TCP 服务器
Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());
//设置服务IP,设置TCP端口号
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 49152);
//定义网络类型,数据连接类型和网络协议UDP
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.SendTo(CmdStart_02, CmdStart_02.Length, SocketFlags.None, ipep);
server.SendTo(CmdSetBias, CmdSetBias.Length, SocketFlags.None, ipep);

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
try
{
server.Connect(sender);
}
catch (System.Exception e)
{
Console.WriteLine("unable to connect the server");
Console.WriteLine(e.ToString());
return;

}
EndPoint Remote = (EndPoint)sender;
Console.WriteLine("Message received from {0}: ", Remote.ToString());
data = new byte[1024];

server.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,1000);
server.Blocking = true;
int recv = 0;
try
{
recv = server.ReceiveFrom(data, ref Remote);
Console.WriteLine(Remote.ToString());
}
catch (System.Exception e)
{
Console.WriteLine(e);
Console.WriteLine(e.ToString());
}
Console.WriteLine("Message received from {0}: ", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

while (true)
{
data = new byte[1024];
// int temp = 0, temp1 = 0;
int CountZ;
try
{
recv = server.ReceiveFrom(data, ref Remote);

}
catch (System.Exception e)
{

Console.WriteLine(e.ToString());
}
CountZ = data[20] * 16777216 + data[21] * 65535 + data[22] * 256 + data[23];
prg1.globalCountZ1 = CountZ;
//输出实时测量到的力传感器数值
double Zforc;
Zforc = prg1.globalCountZ1 / 1000000;
if((count%2000)==0)
Console.WriteLine(Zforc);
count++;
}
// Console.WriteLine("Stopping Client.");
server.Close();

}

提示的异常为:System.Net.Sockets.SocketException 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。可能问题出在 recv = server.ReceiveFrom(data, ref Remote);上面,如果不出现问题Remote会显示正常的连接IPEndPoint,如果出现问题,Remote会为空。
恳求大神指点!!!!!!!
...全文
893 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
越活越不精彩 2012-03-09
  • 打赏
  • 举报
回复
服务器忙,请稍后再拨...

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧