问题描述
我的C#udp通信协议有时候运行正常,有时候出现问题,不知道是什么情况,具体代码如下:
privatestaticvoidRecieveData(){byte[]CmdStart_02=newbyte[8]{0x12,0x34,0x00,0x02,0x00,0x00,0x00,0x00};byte[]CmdSetBias=newbyte[8]{0x12,0x34,0x00,0x42,0x00,0x00,0x00,0x00};byte[]data=newbyte[1024];//stringinput,stringData;//构建TCP服务器Console.WriteLine("ThisisaClient,hostnameis{0}",Dns.GetHostName());//设置服务IP,设置TCP端口号IPEndPointipep=newIPEndPoint(IPAddress.Parse("192.168.1.1"),49152);//定义网络类型,数据连接类型和网络协议UDPSocketserver=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);server.SendTo(CmdStart_02,CmdStart_02.Length,SocketFlags.None,ipep);server.SendTo(CmdSetBias,CmdSetBias.Length,SocketFlags.None,ipep);IPEndPointsender=newIPEndPoint(IPAddress.Any,0);try{server.Connect(sender);}catch(System.Exceptione){Console.WriteLine("unabletoconnecttheserver");Console.WriteLine(e.ToString());return;}EndPointRemote=(EndPoint)sender;Console.WriteLine("Messagereceivedfrom{0}:",Remote.ToString());data=newbyte[1024];server.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,1000);server.Blocking=true;intrecv=0;try{recv=server.ReceiveFrom(data,refRemote);Console.WriteLine(Remote.ToString());}catch(System.Exceptione){Console.WriteLine(e);Console.WriteLine(e.ToString());}Console.WriteLine("Messagereceivedfrom{0}:",Remote.ToString());Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));while(true){data=newbyte[1024];//inttemp=0,temp1=0;intCountZ;try{recv=server.ReceiveFrom(data,refRemote);}catch(System.Exceptione){Console.WriteLine(e.ToString());}CountZ=data[20]*16777216+data[21]*65535+data[22]*256+data[23];prg1.globalCountZ1=CountZ;//输出实时测量到的力传感器数值doubleZforc;Zforc=prg1.globalCountZ1/1000000;if((count%2000)==0)Console.WriteLine(Zforc);count++;}//Console.WriteLine("StoppingClient.");server.Close();}提示的异常为:System.Net.Sockets.SocketException由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。可能问题出在recv=server.ReceiveFrom(data,refRemote);上面,如果不出现问题Remote会显示正常的连接IPEndPoint,如果出现问题,Remote会为空。恳求大神指点!!!!!!!
解决方案
解决方案二:
服务器忙,请稍后再拨...