简体   繁体   中英

Socket.Receive() stuck

I'm practicing my C# after having missed out on it in about two years and writing a client for a server. Anyways, the problem is that Socket.Receive() seems to be stuck (my loop doesn't actually get through, tested it).. Here's my call in Program.cs:

                byte[] buffer = new byte[7];
                hSocket.Receive(buffer, 0, buffer.Length, 500);
And here's the snippet of my 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); 

\n\n
  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); } 
\n\n

I have no idea where I'm going wrong, any help would be appreciated..

Socket.Receive() is a blocking call. If there is no data available it will block until there is data available to read. See MSDN .

If no data is available for reading, the Receive method will block until data is available, unless a time-out value was set by using Socket.ReceiveTimeout. If the time-out value was exceeded, the Receive call will throw a SocketException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM