Weird issue I’m running into. I have an application that listens for UDP packets using the Socket.Poll method…I may be doing something silly, since I’m not terribly deep on writing socket code, but I’m calling that code inside a timer Tick event.
I start the timer using the button module’s buttonPressed event, but once the timer is running, the button no longer raises the buttonPressed event, so I can’t turn off the timer.
I’m guessing that Socket.Poll may not be doing exactly what I think it is, given that the network example I drew from called the method inside a while(true) loop. Wondering what the best practice for socket communication is for Gadgeteer, given that while(true) is not recommended.
Tips or suggestions welcome. Relevant code below:
void timer_Tick(GT.Timer timer)
{
if (CommandReceiver.Poll(-1, SelectMode.SelectRead))
{
byte[] inBuf = new byte[CommandReceiver.Available];
int count = CommandReceiver.ReceiveFrom(inBuf, ref CommandReceiverEndPoint);
string CommandBits = new String(Encoding.UTF8.GetChars(inBuf));
Debug.Print("Command received: " + CommandBits);
uint[] command_buffer = BuildCommandBuffer(CommandBits);
// send command via IR, using OutputCompare instance
IRCommandGenerator.SetBlocking(true, command_buffer, 0, command_buffer.Length, 100, true, 38170);
}
}
and here’s the code that sets up the socket:
CommandReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
CommandReceiverEndPoint = new IPEndPoint(IPAddress.Any, 5000);
CommandReceiver.Bind(CommandReceiverEndPoint);
I’d already had breakpoints in the button event handler code, as well as in the timer code.
Turns out, it was the networking code after all.
When you call Socket.Poll, the first parameter is the length of time (in microseconds) to wait for a response. If you pass it a negative number, it will wait indefinitely, blocking the rest of the code. Changing this to a positive number resolved the issue with the buttonPressed handler not being called.
I just found out from devhammer’s first video (link below) that I was never exiting my application entry point (ProgramStarted method) because I was doing an inifinite timeout with the socket poll method. After looking at the Thread class it was super easy to get by this.
Instead of calling my connect method directly that did the socket initialization and the infinite poll, I simply had to wrap that call in a new thread and call start on it. no other code changes necessary! Now my poll method is running forever on another thread.