其中使用到了Socket的非阻塞方法来接受数据,然后交由另一个线程进行命令的解释(只是将命令整条提取出来放入队列或者列表中),客户端测试程序有空再放出吧,测试的话用网络调试软件发ascii字符就可以

[6]abcd12
6为长度,如果之后的数据长度超过6,则只提取有用的部分,其余的丢弃。
abcd12为命令字符串(提取到队列或列表中的部分)
 
由于到时候是运行在回环地址上,因此没有过多考虑网络异常方面的问题。
 
另外自己对设计模式一直没有研究过,代码结构啥的可能比较乱,将就看看吧。有问题的话请留言,谢谢。
 
  1. using System; 
  2. using System.Net; 
  3. using System.Net.Sockets; 
  4. using System.Text; 
  5. using System.Threading; 
  6. using System.Data; 
  7. using System.Collections.Generic; 
  8. using System.Text.RegularExpressions; 
  9.    
  10. // State object for reading client data asynchronously 
  11. public class StateObject 
  12.     // Client  socket. 
  13.     public Socket workSocket = null
  14.     // Size of receive buffer. 
  15.     public const int BufferSize = 1024; 
  16.     // Receive buffer. 
  17.     public byte[] buffer = new byte[BufferSize]; 
  18.     // Received data string. 
  19.     public StringBuilder sb = new StringBuilder(); 
  20.     // Offset 
  21.     public int counter = 0; 
  22.     // 
  23.     public bool isDisconnected = false
  24.     // 
  25.     public Thread dataParseThread = null
  26.     // 
  27.     public ManualResetEvent readDone = new ManualResetEvent(false); 
  28.     // 
  29.     public ManualResetEvent ProcessDone = new ManualResetEvent(false); 
  30.    
  31. public class AsynchronousSocketListener 
  32.     public static int Main(String[] args) 
  33.     { 
  34.         //StartListening(); 
  35.    
  36.         AsyncSocketServer asyncServer = new AsyncSocketServer(); 
  37.         asyncServer.StartListening(); 
  38.    
  39.         return 0; 
  40.     } 
  41.    
  42. public class AsyncSocketServer 
  43.     // Thread signal. 
  44.     private ManualResetEvent allDone = new ManualResetEvent(false); 
  45.    
  46.     public AsyncSocketServer() 
  47.     { 
  48.     } 
  49.    
  50.     public void StartListening() 
  51.     { 
  52.         // Data buffer for incoming data. 
  53.         byte[] bytes = new Byte[1024]; 
  54.    
  55.         // Establish the local endpoint for the socket. 
  56.         // The DNS name of the computer 
  57.         // running the listener is "host.contoso.com". 
  58.         IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1"); 
  59.         IPAddress ipAddress = ipHostInfo.AddressList[0]; 
  60.         IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 
  61.    
  62.         // Create a TCP/IP socket. 
  63.         Socket listener = new Socket(AddressFamily.InterNetwork, 
  64.             SocketType.Stream, ProtocolType.Tcp); 
  65.    
  66.         // Bind the socket to the local endpoint and listen for incoming connections. 
  67.         try 
  68.         { 
  69.             listener.Bind(localEndPoint); 
  70.             listener.Listen(10); 
  71.    
  72.             while (true
  73.             { 
  74.                 // Set the event to nonsignaled state. 
  75.                 allDone.Reset(); 
  76.    
  77.                 // Start an asynchronous socket to listen for connections. 
  78.                 Console.WriteLine("Waiting for a connection..."); 
  79.                 listener.BeginAccept( 
  80.                     new AsyncCallback(AcceptCallback), 
  81.                     listener); 
  82.    
  83.                 // Wait until a connection is made before continuing. 
  84.                 allDone.WaitOne(); 
  85.             } 
  86.    
  87.         } 
  88.         catch (Exception e) 
  89.         { 
  90.             Console.WriteLine(e.ToString()); 
  91.         } 
  92.    
  93.         Console.WriteLine("\nPress ENTER to continue..."); 
  94.         Console.Read(); 
  95.    
  96.     } 
  97.    
  98.     public void AcceptCallback(IAsyncResult ar) 
  99.     { 
  100.         // Signal the main thread to continue. 
  101.         allDone.Set(); 
  102.    
  103.         // Get the socket that handles the client request. 
  104.         Socket listener = (Socket)ar.AsyncState; 
  105.         Socket handler = listener.EndAccept(ar); 
  106.    
  107.         // Create the state object. 
  108.         StateObject state = new StateObject(); 
  109.         state.workSocket = handler; 
  110.    
  111.         DataProcessor dateProcessor = new DataProcessor(state); 
  112.    
  113.         Thread t = new Thread(dateProcessor.ParseRowData); 
  114.         state.dataParseThread = t; 
  115.         t.Start(); 
  116.    
  117.         IAsyncResult iar = handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
  118.             new AsyncCallback(ReadCallback), state); 
  119.     } 
  120.    
  121.     public void ReadCallback(IAsyncResult ar) 
  122.     { 
  123.         String content = String.Empty; 
  124.    
  125.         // Retrieve the state object and the handler socket 
  126.         // from the asynchronous state object. 
  127.         StateObject state = (StateObject)ar.AsyncState; 
  128.         Socket handler = state.workSocket; 
  129.    
  130.         try 
  131.         { 
  132.    
  133.             // Read data from the client socket.  
  134.             int bytesRead = handler.EndReceive(ar); 
  135.    
  136.             if (bytesRead <= 0) 
  137.             { 
  138.                 Console.WriteLine("Server can't handle because received data length is zero..."); 
  139.                 handler.Shutdown(SocketShutdown.Both); 
  140.                 handler.Close(); 
  141.                 return
  142.             } 
  143.    
  144.             state.readDone.Reset(); 
  145.    
  146.             string tmp = System.Text.Encoding.ASCII.GetString(state.buffer, 0, bytesRead); 
  147.             state.sb.Append(tmp); 
  148.    
  149.             Console.WriteLine(state.sb.ToString()); 
  150.    
  151.             state.ProcessDone.Set(); 
  152.             state.readDone.WaitOne(); 
  153.    
  154.             IAsyncResult iar = handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
  155.                 new AsyncCallback(ReadCallback), state); 
  156.    
  157.         } 
  158.         catch (Exception ex) 
  159.         { 
  160.             ; 
  161.         } 
  162.     } 
  163.    
  164.     private void Send(Socket handler, String data) 
  165.     { 
  166.         // Convert the string data to byte data using ASCII encoding. 
  167.         byte[] byteData = Encoding.ASCII.GetBytes(data); 
  168.    
  169.         // Begin sending the data to the remote device. 
  170.         handler.BeginSend(byteData, 0, byteData.Length, 0, 
  171.             new AsyncCallback(SendCallback), handler); 
  172.     } 
  173.    
  174.     private void SendCallback(IAsyncResult ar) 
  175.     { 
  176.         try 
  177.         { 
  178.             // Retrieve the socket from the state object. 
  179.             Socket handler = (Socket)ar.AsyncState; 
  180.    
  181.             // Complete sending the data to the remote device. 
  182.             int bytesSent = handler.EndSend(ar); 
  183.             Console.WriteLine("Sent {0} bytes to client.", bytesSent); 
  184.    
  185.             handler.Shutdown(SocketShutdown.Both); 
  186.             handler.Close(); 
  187.    
  188.         } 
  189.         catch (Exception e) 
  190.         { 
  191.             Console.WriteLine(e.ToString()); 
  192.         } 
  193.     } 
  194.    
  195. public class DataProcessor 
  196.     private StateObject st = null
  197.     // hold command txt 
  198.     private static List<string> commandQueue = new List<string>(); 
  199.    
  200.     public DataProcessor(StateObject st) 
  201.     { 
  202.         this.st = st; 
  203.     } 
  204.     //  
  205.     private Mutex addCommandMutex = new Mutex(false"MUTEX_ADD_COMMAND"); 
  206.    
  207.     public void ParseRowData() 
  208.     { 
  209.         Regex regex = new Regex(@"\[([\d]+)\]"); 
  210.    
  211.         while (true
  212.         { 
  213.             st.ProcessDone.WaitOne(); 
  214.             if (st.sb.Length > 0) 
  215.             { 
  216.                 Console.WriteLine("Start to parse data..."); 
  217.    
  218.                 string tmp = st.sb.ToString(); 
  219.                 Match match = regex.Match(tmp); 
  220.    
  221.                 if (match.Success == false
  222.                     Console.WriteLine("Not matched..."); 
  223.    
  224.                 while (match.Success) 
  225.                 { 
  226.                     string strLen = match.Groups[1].Value; 
  227.                     int len = int.Parse(strLen); 
  228.    
  229.                     string strMatch = match.ToString(); 
  230.                     if (tmp.Length - strMatch.Length - match.Index >= len) 
  231.                     { 
  232.                         string strToAdd = tmp.Substring(strMatch.Length + match.Index, len); 
  233.                         Console.WriteLine("Adding command: " + strToAdd); 
  234.                         AddToCommandQueue(strToAdd); 
  235.                         st.sb.Remove(0, match.Index + strMatch.Length + len); 
  236.                     } 
  237.                     else 
  238.                     { 
  239.                         Console.WriteLine("The string is not completed, waiting the reset data..."); 
  240.                         break
  241.                     } 
  242.    
  243.                     PrintCommandQueue(); 
  244.    
  245.                     tmp = st.sb.ToString(); 
  246.                     match = regex.Match(tmp); 
  247.                 } 
  248.    
  249.                 Console.WriteLine("End parsing data..."); 
  250.             } 
  251.             else 
  252.             { 
  253.                 Console.WriteLine("No data will be processed..."); 
  254.             } 
  255.    
  256.             st.readDone.Set(); 
  257.             st.ProcessDone.Reset(); 
  258.         } 
  259.     } 
  260.    
  261.     private void AddToCommandQueue(string str) 
  262.     { 
  263.         addCommandMutex.WaitOne(); 
  264.         commandQueue.Add(str); 
  265.         addCommandMutex.ReleaseMutex(); 
  266.     } 
  267.    
  268.     public static void PrintCommandQueue() 
  269.     { 
  270.         foreach(string item in commandQueue) 
  271.         { 
  272.             Console.WriteLine(item); 
  273.         } 
  274.     }