我在大约两年的时间里错过了我的C#,并为服务器编写了一个客户端,现在我正在练习它。无论如何,问题是Socket.Receive()似乎被卡住了(我的循环实际上没有通过测试它)..下面是我在Program.cs中的调用:
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);
}
I have no idea where I'm going wrong, any help would be appreciated..发布于 2014-04-04 21:54:10
Socket.Receive()是一个阻塞调用。如果没有可用的数据,它将被阻塞,直到有数据可读。参见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.
https://stackoverflow.com/questions/22864715
复制相似问题