日期:2014-05-20 浏览次数:21151 次
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace SocketDemo { static class Program { static void Main(string[] argv) { Socket sktltn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sktltn.Bind(new IPEndPoint(IPAddress.Any, 12345)); sktltn.Listen(30); while (true) { Socket sk = sktltn.Accept(); ThreadPool.QueueUserWorkItem(p => { Socket skc = (Socket)sk; byte[] array = new byte[10240]; int offset = 0; while (true) { int len = skc.Receive(array, offset, array.Length - offset, SocketFlags.None); if (len == 0) { break; } offset += len; } string content = Encoding.UTF8.GetString(array, 0, offset); Console.WriteLine("> " + content); }, sk); } } } }
------解决方案--------------------
把这段另起一个线程就不会阻塞ui线程了
new Thread(new ThreadStart(delegate{ Socket sktltn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sktltn.Bind(new IPEndPoint(IPAddress.Any, 12345)); sktltn.Listen(30); while (true) { Socket sk = sktltn.Accept(); ThreadPool.QueueUserWorkItem(p => { Socket skc = (Socket)sk; byte[] array = new byte[10240]; int offset = 0; while (true) { int len = skc.Receive(array, offset, array.Length - offset, SocketFlags.None); if (len == 0) { break; } offset += len; } string content = Encoding.UTF8.GetString(array, 0, offset); Console.WriteLine("> " + content); }, sk); } })).Start();