求一个C#(winform)程序Demo,要求用线程池实现SOCKET通讯,有服务端和客户端。在线等。。各位大侠来解啊!!!
------解决方案--------------------------------------------------------
服务端
- C# code
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线程了
- C# code
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();