C# socket problem with receiving data
I'm currently writing a test program for an network attached mircocontroller which controls a led light.
When I'm trying to receive an answer from the remote host the whole procedure gets stuck in the socket.receive function.
I'm sending a few bytes of data using a socket to the remote host. Then I listen for incomming data. But at the point where I receive the data the program just stops without an exception or anything.
Send-Function :
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);
}
Extract from 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 }
}
And here the sock_receive function where everything gets stuck :
开发者_运维技巧 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);
}
I hope you guys can help me.
Greetings
n0pt3x
Am I right that m_socket is a server socket which listens for connections? Naturally, you can't receive data from it, you have to call Accept() first, and read from the socket that it returns.
精彩评论