C# socket伺服器非同步監聽注意事項
阿新 • • 發佈:2018-11-21
private static int port = Convert.ToInt32(ConfigurationManager.AppSettings["LogServerPort"]); public static void StartListening() { IPAddress ipAddress = System.Net.IPAddress.Parse("0.0.0.0"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and // listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(1000); // Start listening for connections. while (true) { try { Socket handler = listener.Accept(); //accept 有三次握手過程,第一次握手成功,Accept()方法就停止阻塞 Thread t = new Thread(resMsg); t.IsBackground = true; t.Start(handler); } catch (Exception ex) { BaseFunc.WriteInLog(ex.Message + ex.StackTrace); Thread.Sleep(10000); } } } catch (Exception e) { BaseFunc.WriteInLog(e.Message + e.StackTrace); } }
/// <summary> /// 迴圈接收客戶端發來的訊息 /// </summary> /// <param name="obj"></param> static void resMsg(object obj) { int count = 0; try { Socket uSocket = obj as Socket; //1.防止Accept第三次握手沒有成功,Receive()方法就一直處於阻塞狀態!!!報錯資訊(由於連線方在一段時間後沒有正確答覆或連線的主機沒有反應,連線嘗試失敗) //2.接收超時限制 uSocket.ReceiveTimeout = 3000; //很重要!!! //開始呼叫Receive()函式 ...... } }
TCP三次握手連線