【发布时间】:2014-04-04 13:50:05
【问题描述】:
在大约两年内错过了 C# 并为服务器编写客户端后,我正在练习我的 C#。无论如何,问题是 Socket.Receive() 似乎被卡住了(我的循环实际上并没有通过,测试它)。这是我在 Program.cs 中的调用:
byte[] buffer = new byte[7];
hSocket.Receive(buffer, 0, buffer.Length, 500);这是我的 APISocket.cs 的 sn-p 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);
}
我不知道我哪里出错了,任何帮助将不胜感激..
【问题讨论】:
-
你确定服务器在监听吗?套接字初始化代码是什么样的?
-
是的。我正在模拟登录服务器的启动器,它适用于旧启动器。我知道我的数据包是正确的,套接字是异步初始化的,这可能是个问题吗?
-
异步初始化是什么意思?这可能是个问题,是的。
-
我正在异步建立我的套接字连接,这就是我的意思。
-
添加该代码。如果我没记错的话,这样做错误的方式可能会导致您所描述的内容。