我正在为一个控制LED灯的网络连接微控制器编写一个测试程序。
当我尝试从远程主机接收答案时,整个过程卡在socket.receive函数中。
我使用套接字向远程主机发送几个字节的数据。然后我听取了数据。但是在我收到数据的时候,程序就会在没有例外的情况下停止。
发送功能:
public void Send(Command cmd)
{
switch (cmd.command)
{
case CommandType.SetAll:
send_data(SET_COLOR_ALL, cmd.data, 3);
break;
case CommandType.SetRed:
send_data(SET_COLOR_RED, cmd.data, 1);
break;
case CommandType.SetGreen:
send_data(SET_COLOR_GREEN, cmd.data, 1);
break;
case CommandType.SetBlue:
send_data(SET_COLOR_BLUE, cmd.data, 1);
break;
case CommandType.GetColor:
Debug.WriteLine("Sending request...");
send_data(GET_COLOR, cmd.data, 0);
read_data(); //here it gets stuck !
break;
}
m_socket.Disconnect(true);
}
从read_data()中提取
private void read_data()
{
Debug.WriteLine("Called read_data()");
byte[] t_buffer = new byte[4];
try
{
if(!m_socket.Connected)
m_socket.Listen(10000);
sock_receive(m_socket, ref t_buffer, 0, t_buffer.Length, 10000);
}
catch (Exception ex) {
throw ex;
}
finally { // do some stuff here }
}
这里是sock_receive函数,其中一切都被卡住了:
public static void sock_receive(Socket socket,ref byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int received = 0; // how many bytes is already received
do
{
Debug.WriteLine("In Loop..");
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try
{
//here it gets stuck !
received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
Debug.WriteLine("Byte arrived, received : " + received.ToString());
}
catch (SocketException ex)
{
Debug.WriteLine("Socket exception !");
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (received < size);
}
我希望你们能帮帮我。
问候
n0pt3x
答案 0 :(得分:0)
我是对的,m_socket是一个侦听连接的服务器套接字吗?当然,您无法从中接收数据,您必须先调用Accept(),然后从它返回的套接字中读取。