0
我在約兩年內錯過了它併爲服務器編寫客戶端後正在練習C#。無論如何,問題是,Socket.Receive()似乎被卡住了(我的循環實際上並沒有通過測試)。這是我在Program.cs中的調用:Socket.Receive()卡住
byte[] buffer = new byte[7];
hSocket.Receive(buffer, 0, buffer.Length, 500);
這是我的APISocket.cs的片段
我不知道我要去哪裏錯了,任何幫助,將不勝感激..public bool Connect(string ServerIP, int ServerPort, int Timeout) { TimeoutObject.Reset(); SocketException = null; try { Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint IPEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), ServerPort); object state = new object(); Socket.BeginConnect(IPEndPoint, new AsyncCallback(CallBackMethod), state);
if (TimeoutObject.WaitOne(Timeout, false)) { if (IsConnected) return true; else return false; } else { return false; } } catch (Exception Ex) { SocketException = Ex; } return false; } private void CallBackMethod(IAsyncResult AsyncResult) { try { IsConnected = false; if (Socket.Connected) { IsConnected = true; } } catch (Exception Ex) { IsConnected = false; SocketException = Ex; } finally { TimeoutObject.Set(); } } public void Receive(byte[] buffer, int offset, int size, int timeout) { SocketException = null; int startTick = Environment.TickCount; int received = 0; do { if (Environment.TickCount > startTick + timeout) { SocketException = new Exception("Timeout."); return; } try { received += Socket.Receive(buffer, offset + received, size - received, SocketFlags.None); } catch (SocketException Ex) { if (Ex.SocketErrorCode == SocketError.WouldBlock || Ex.SocketErrorCode == SocketError.IOPending || Ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { Thread.Sleep(30); } else { SocketException = Ex; return; } } } while (received < size); }
你確定服務器正在監聽嗎?套接字初始化代碼是什麼樣的? – kolosy
是的。我正在模擬一個登錄服務器的啓動器,它可以與舊啓動器一起工作。我知道我的數據包是正確的,套接字是異步初始化的,這可能是一個問題嗎? –
你是什麼意思的異步初始化?這可能是一個問題,是的。 – kolosy