问题描述
求助各位大神,想用UDP与多台客户端通信,下面的代码如果光接收,正常可以用,加入发送后,就会有阻塞,哪位好人指点一下usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Collections;usingSystem.Threading;namespaceudpServer0929{classProgram{staticvoidMain(string[]args){Programa=newProgram();a.BeginStart();Threadb=newThread(a.Send);b.Start();}publicvoidBeginStart(){ArrayListclient=newArrayList();try{Socketnewsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);IPEndPointip=newIPEndPoint(IPAddress.Any,8001);newsock.Bind(ip);Threadth=newThread(Recive);th.Start(newsock);Console.WriteLine("服务端开启监听");Console.ReadKey();}catch(Exceptionex){}}Dictionary<EndPoint,Socket>dicSocket=newDictionary<EndPoint,Socket>();voidRecive(objecto){Socketnewsock=oasSocket;IPEndPointsender=newIPEndPoint(IPAddress.Any,0);EndPointRemote=(EndPoint)sender;intrecv;while(true){try{byte[]buffer=newbyte[1024*1024*2];recv=newsock.ReceiveFrom(buffer,refRemote);Console.WriteLine("Messagereceivedfrom{0}:",Remote);Console.WriteLine(Encoding.ASCII.GetString(buffer,0,recv));//newsock.SendTo(buffer,buffer.Length,SocketFlags.None,refRemote);dicSocket.Add(Remote,newsock);}catch(Exceptionex){}}}
解决方案
解决方案二:
你所用的都是用阻塞的方法你改用m_Socket.BeginReceiveFrom()接收m_Socket.BeginSendTo()发送,就不会阻塞了当然你的程序要改一下,不能用while(true)来整。像这样子///<summary>///开始从指定网络设备中异步接收数据。///</summary>privatevoidBeginReceive(){ReceiveDatabufferData=newReceiveData();//使用对象池//kickoffanasyncreadm_Socket.BeginReceiveFrom(bufferData.Data,0,bufferData.Data.Length,SocketFlags.None,refbufferData.RemoteEndPoint,m_OnReceive,bufferData);}///<summary>///接收异步数据///</summary>///<paramname="asyncResult"></param>privatevoidOnReceive(IAsyncResultasyncResult){ReceiveDatabuffer=(ReceiveData)asyncResult.AsyncState;try{intlength=m_Socket.EndReceiveFrom(asyncResult,refbuffer.RemoteEndPoint);if(length>0){byte[]buferData=newbyte[length];System.Buffer.BlockCopy(buffer.Data,0,buferData,0,length);BeginReceive();return;}}catch{m_Running=false;}}
解决方案三:
是的,可以试试.net4.5的非阻塞调用
解决方案四:
非常感谢各位大侠