select是一種比較古老但一直被證明性能很好的socket模式,它可以讓你以消息驅(qū)動(dòng)的模式書寫socket程序。網(wǎng)上C++的例子很多,但C#的例子極少。 上代碼: - namespace Server
- {
- class Program
- {
-
- public static ManualResetEvent allDone = new ManualResetEvent(false);
-
- private static Socket handler = null;
- private static ArrayList g_CliSocketArr = new ArrayList();
- private static Object thisLock = new Object();
- public Program()
- {
- }
-
- public static void StartListening() {
-
- byte[] bytes = new Byte[1024];
-
-
- IPAddress ipAddress = IPAddress.Parse("0.0.0.0");
- IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
-
-
- Socket listener = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp );
-
-
- try {
- listener.Bind(localEndPoint);
- listener.Listen(100);
-
-
-
- Console.WriteLine("Waiting for a connection...");
-
- Thread worker = new Thread(new ThreadStart(WorkerThread));
- worker.Start();
- while (true)
- {
- Socket sClient = listener.Accept();
- Console.WriteLine("There is a new connection.");
- g_CliSocketArr.Add(sClient);
-
- }
-
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
-
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
-
- }
- public static void WorkerThread()
- {
- Socket socket1 = null;
- ArrayList readList = new ArrayList();
-
- while (true)
- {
- lock (thisLock)
- {
- readList.Clear();
- for (int i = 0; i < g_CliSocketArr.Count; i++)
- {
- readList.Add(g_CliSocketArr[i]);
- }
- }
- if (readList.Count <= 0)
- {
- Thread.Sleep(100);
- continue;
- }
- try
- {
- Socket.Select(readList, null, null, 500);
- for (int i = 0; i < readList.Count; i++)
- {
- socket1 = (Socket)readList[i];
- Console.WriteLine("There is a new message from client.");
- byte[] buffer = new byte[1024];
-
- int recLen = socket1.Receive(buffer);
- if(recLen > 0)
- {
-
- }
- else
- {
- Console.WriteLine("Rece 0 length.");
- for (int ii = 0; ii < g_CliSocketArr.Count; ii++)
- {
- Socket s = (Socket)g_CliSocketArr[ii];
- if (s == socket1)
- g_CliSocketArr.RemoveAt(ii);
- }
- socket1.Shutdown(SocketShutdown.Both);
- socket1.Close();
- break;
- }
- socket1.Send(buffer,recLen, SocketFlags.None);
-
- }
- }
- catch (SocketException e)
- {
- Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
-
- for (int ii = 0; ii < g_CliSocketArr.Count; ii++)
- {
- Socket s = (Socket)g_CliSocketArr[ii];
- if (s == socket1)
- g_CliSocketArr.RemoveAt(ii);
- }
- socket1.Shutdown(SocketShutdown.Both);
- socket1.Close();
- }
- }
-
- }
-
- static void Main(string[] args)
- {
- StartListening();
- }
-
- }
-
- }
|