I've had more time with this, so I started pulling the code apart making it simplier to understand (for the way I think atleast). Starting with the receiving part, have the code done, but I'm having 2 issues.
- The RemoteEndPoint IP is still always 0.0.0.0, I need to figure out the IP that is sending the message so I can send the results back to that same IP.
- I have it working to read 1 message, but then everything craps out and even though it says there are 4 bytes available to read (once I send another message) the 'bytes = listener.Receive(rxBuff);' always return 0 and leaves the byte array empty. Am I missing a step?
If anyone can help at all it would be much appreciated, hopefully I'm just missing a step somewhere?
Program.cs
using System; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware; using SecretLabs.NETMF.Hardware.Netduino; using System.IO; using Microsoft.SPOT.Net.NetworkInformation; namespace UDPMag_NetduinoPlus2 { public class Program { private static IPAddress myIPAddress = null; private static int dataPort = 8888; private static UDPReceiver udpReceiver = null; public static void Main() { //Make Sure Network is setup. SetupTCPIPFromSD(); //Setup Listener to handle incoming Commands, this runs a listener thread. udpReceiver = new UDPReceiver(new IPEndPoint(myIPAddress, dataPort)); udpReceiver.OnMessageReceived += new UDPReceiver.MessageReceived(udpReceiver_OnMessageReceived); //The sender event is going to be created when we get our first message in the OnMessageReceived Handler. //Keep the thread alive as we are using all listeners and events. Thread.Sleep(Timeout.Infinite); } static void udpReceiver_OnMessageReceived(string message, IPEndPoint sender) { Debug.Print(sender.Address.ToString() + ": " + message); } private static void SetupTCPIPFromSD() { NetworkInterface ethernet1 = NetworkInterface.GetAllNetworkInterfaces()[0]; if (ethernet1.IPAddress == "192.168.5.100") { //Setup Defaults as SD Card is not working currently... string LocalIPAddress = "10.201.1.99"; string SubNetMask = "255.255.255.0"; string Gateway = "10.201.1.254"; if (File.Exists(@"IPData.txt")) { using (FileStream filestream = new FileStream(@"IPData.txt", FileMode.Open)) { StreamReader reader = new StreamReader(filestream); Debug.Print(reader.ReadToEnd()); reader.Close(); } } ethernet1.EnableStaticIP(LocalIPAddress, SubNetMask, Gateway); } myIPAddress = IPAddress.Parse(ethernet1.IPAddress); } } }
UDPReceiver.cs [Class]
using System; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.SPOT; using EthernetSocketDefs; namespace UDPMag_NetduinoPlus2 { public class UDPReceiver { public delegate void MessageReceived(string message, IPEndPoint sender); public event MessageReceived OnMessageReceived = null; private IPEndPoint localEndPoint = null; private IPEndPoint remoteEndPoint = null; public UDPReceiver(IPEndPoint ipeo) { this.localEndPoint = ipeo; // Create a delegate of type "ThreadStart", which is a pointer to the // worker thread's main function ThreadStart delegateWorkerThread = new ThreadStart(Main); // Next create the actual thread, passing it the delegate to the main function Thread threadWorker = new Thread(delegateWorkerThread); // Now start the thread. threadWorker.Start(); } #region The actual worker thread code /// <summary> /// This is a method which does the work of the worker thread. /// </summary> private void Main() { int bytes = 0; // Holds number of bytes received byte[] rxBuff = null; // Holds received message // Create a "UDP" socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // Bind the socket to the local endpoint and listen for incoming UDP datagrams. try { listener.Bind(localEndPoint); } catch (SocketException se) { SocketErrorCodes errorCode = (SocketErrorCodes)se.ErrorCode; switch (errorCode) { case SocketErrorCodes.NetworkIsDown: Debug.Print("Socket Exception on creation: NetworkIsDown"); break; default: Debug.Print("Socket Exception error: " + errorCode); break; } } listener.ReceiveTimeout = 1000; // Loop forever while (true) { bytes = 0; string cause = "unknown"; try { //Debug.Print("Attempt to listen on " + localEndPoint.ToString()); if (listener.Available > 0) { rxBuff = new byte[listener.Available]; bytes = listener.Receive(rxBuff); } else { cause = "No Data Available"; } } catch (Exception ge) { if (ge is SocketException) { SocketErrorCodes errorCode = (SocketErrorCodes)((SocketException)ge).ErrorCode; switch (errorCode) { case SocketErrorCodes.NetworkIsDown: // The network is not connected. cause = "NetworkIsDown"; break; case SocketErrorCodes.ConnectionTimedOut: // Connection timed out - e.g. nothing received cause = "ConnectionTimedOut"; break; default: Debug.Print("Socket Exception error: " + errorCode); break; } } else cause = ge.Message; } if (bytes == 0) { Debug.Print("Nothing received: reason - " + cause); } else { // set the remote end point so we know who sent us the data. remoteEndPoint = listener.RemoteEndPoint as IPEndPoint; //Convert to string. System.Text.UTF8Encoding e = new System.Text.UTF8Encoding(); string txtMessage = new string(e.GetChars(rxBuff)); // Call Event! if (OnMessageReceived != null) OnMessageReceived(txtMessage, remoteEndPoint); } } } private bool SocketConnected(Socket s) { return !(s.Poll(1000, SelectMode.SelectRead) & (s.Available == 0)); } #endregion } }