日期:2014-05-18 浏览次数:21063 次
static void Receive(object state) { Socket socket = state as Socket; EndPoint otherEnd = new IPEndPoint(IPAddress.Any, 0); byte[] buffer = new byte[6400]; try { socket.ReceiveFrom(buffer, ref otherEnd); } catch (SocketException se) { Console.WriteLine(se.Message); } } static void Main() { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(IPAddress.Any, 12345)); ThreadPool.QueueUserWorkItem(Receive, socket); Thread.Sleep(2 * 1000); socket.Shutdown(SocketShutdown.Both); socket.Close(); //<--- Console.WriteLine("socket closed"); Console.ReadLine(); }
------解决方案--------------------
试试看异步吧
------解决方案--------------------
放个public static的变量,用于在下次receive前判断,
比如
while(true)
{
if (var)
{
break;
}
receive...
}