UDP Client on Fez Spider

Hello, even though I tried I could not connect with the FEZ Spider to a UDP server, for more codes I found on the forum I fail to connect with the platform, using the address 127.0.0.1 emulator running, but not well with the hardware.

I can successfully ping, and when I use the UDP server examples working properly but I can not run as a client.

I use the Hercules software to open the UDP server.

The firmware version is 4.2.10.1

Anyone can help me?

Hi Andre, what I’m doing is:

I open the Hercules program on my pc, I connect via a crossover cable the FEZ Spider and PC.

Everything has fixed addresses to avoid problems with DHCP.

I’m using the next code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Microsoft.SPOT;

using GHI.Premium.Net;

namespace UDP_Client_42
{
public class Program
{
public static void Main()
{
Socket SendingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//IPAddress Send_to_Address = IPAddress.Parse(“192.168.1.10”); //PC
IPAddress Send_to_Address = IPAddress.Parse(“127.0.0.1”); // Emulator
IPEndPoint sending_end_point = new IPEndPoint(Send_to_Address, 10001);

        byte[] buff = Encoding.UTF8.GetBytes("prueba de socket");

        try
        {
            //ns.WriteByte(55);
            SendingSocket.SendTo(buff, sending_end_point);
        }
        catch (Exception Send_Ex)
        {
            Debug.Print(Send_Ex.Message);

        }
        Thread.Sleep(Timeout.Infinite);
    }

}

}

Thank you.

127.0.0.1 is not a valid network address. It’s not “routable” between devices. You need actual (fixed or DHCP allocated) network addresses for this to work. So I think you need to get the addressing sorted out before you can take this further…

Thanks Andre for your comment, I’ll put the code with the correct format.

Hello Brett, I use the 127.0.0.1 IP only for the emulator, using the configuration tools for the device, now has the IP to 192.168.1.9, and my server the 192.168.1.10 in the port 10001.

when I run the code in the emulator everything works properly, but not with the device, (changing the server IP and using the cross cable).

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Microsoft.SPOT;

using GHI.Premium.Net;

namespace UDP_Client_42
{
    public class Program
    {
        public static void Main()
        {
            Socket SendingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //IPAddress Send_to_Address = IPAddress.Parse("192.168.1.10"); // Device
            IPAddress Send_to_Address = IPAddress.Parse("127.0.0.1");        // Emulator
            IPEndPoint sending_end_point = new IPEndPoint(Send_to_Address, 10001);

            //NetworkStream ns = new NetworkStream(SendingSocket);
            

            byte[] buff = Encoding.UTF8.GetBytes("prueba de socket");

            try
            {
                //ns.WriteByte(55);
                SendingSocket.SendTo(buff, sending_end_point);
            }
            catch (Exception Send_Ex)
            {
                Debug.Print(Send_Ex.Message);

            }
            Thread.Sleep(Timeout.Infinite);
        }

    }
}

thanks.

@ Gabo2 -

Are you using wifi, built-in Ethernet, ENC28 or something else?

Hello Dat, I’m using the J11D Socket included in the FEZ Spider Kit.

@ Gabo2 -

Then show us your code (full and simple) then we can copy / paste and test it quickly.

In your post #5, it looks like there is no code for JD11 module

Shouldn’t the network tack be routed to the proper interface first? (there are 3 of them built-in, enc28 and wifi)

Dat, the code is based on a GUS example of a httpListener.

using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Net;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using GHI.Premium.Net;
using Microsoft.SPOT.Hardware;



namespace MFConsoleNetworking
{
    public class Program
    {
        static EthernetBuiltIn Eth1 = new EthernetBuiltIn();
        
        static byte[] outBuffer;
        static public ManualResetEvent NetworkAvailablityBlocking = null;
        static string myIP = "192.168.1.9";
        private const int port = 10001;
        

        static Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram , ProtocolType.Udp);
        static IPEndPoint DestinationEndPoint = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 1, 10 }), port);
       


        public static void Main()
        {
            Eth1.Open();

            NetworkInterfaceExtension.AssignNetworkingStackTo(Eth1);

            Eth1.CableConnectivityChanged += new EthernetBuiltIn.CableConnectivityChangedEventHandler(Eth1_CableConnectivityChanged);
            Eth1.NetworkAddressChanged += new NetworkInterfaceExtension.NetworkAddressChangedEventHandler(Eth1_NetworkAddressChanged);

            Eth1.NetworkInterface.EnableStaticIP(myIP, "255.255.255.0", "192.168.1.1");
            


            if (!Eth1.IsCableConnected)
            {
                NetworkAvailablityBlocking = new ManualResetEvent(false);

                do
                {
                    if (!Eth1.IsCableConnected)
                    {
                        Debug.Print("Ethernet cable is not connected yet.");
                    }
                    else
                        break;
                }
                while (!NetworkAvailablityBlocking.WaitOne(5000, false));
            }

            while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any)
            {
                Debug.Print("IP address is not set yet.");
            }

            Debug.Print("IP address is set");

            string str = "Hello World!";
            byte[] outBuffer = Encoding.UTF8.GetBytes(str);

            try
            {
                Debug.Print("Running HttpServer");
                Debug.Print("Type this IP address to access the webpage: " + Eth1.NetworkInterface.IPAddress);

                //RunServer();
                try
                {
                    //Conection.Connect(ep);
                     byte[] buf = Encoding.UTF8.GetBytes("Information to send");
                     ClientSocket.SendTo(buf, DestinationEndPoint );
                    Debug.Print("Ok");
                }
                catch { }
                finally { ClientSocket.Close(); }

                Thread.Sleep(Timeout.Infinite);


            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
            }
        }


        static void Eth1_CableConnectivityChanged(object sender, EthernetBuiltIn.CableConnectivityEventArgs e)
        {
            Debug.Print("Built-in Ethernet Cable is " + (e.IsConnected ? "Connected!" : "Disconneced!"));

            if (e.IsConnected)
                NetworkAvailablityBlocking.Set();
        }

        static void Eth1_NetworkAddressChanged(object sender, EventArgs e)
        {
            Debug.Print("New address for The built-in Ethernet Network Interface ");

            Debug.Print("Is DhCp enabled: " + Eth1.NetworkInterface.IsDhcpEnabled);
            Debug.Print("Is DynamicDnsEnabled enabled: " + Eth1.NetworkInterface.IsDynamicDnsEnabled);
            Debug.Print("NetworkInterfaceType " + Eth1.NetworkInterface.NetworkInterfaceType);
            Debug.Print("Network settings:");
            Debug.Print("IP Address: " + Eth1.NetworkInterface.IPAddress);
            Debug.Print("Subnet Mask: " + Eth1.NetworkInterface.SubnetMask);
            Debug.Print("Default Getway: " + Eth1.NetworkInterface.GatewayAddress);
            Debug.Print("Number of DNS servers:" + Eth1.NetworkInterface.DnsAddresses.Length);

            for (int i = 0; i < Eth1.NetworkInterface.DnsAddresses.Length; i++)
                Debug.Print("DNS Server " + i.ToString() + ":" + Eth1.NetworkInterface.DnsAddresses[i]);

            Debug.Print("------------------------------------------------------");
        }

        internal static void RunServer()
        {
            HttpListener listener = new HttpListener("http");
            listener.Start();

            while (true)
            {
                HttpListenerResponse response = null;
                HttpListenerContext context = null;

                try
                {
                    context = listener.GetContext();
                    response = context.Response;
                    HttpListenerRequest request = context.Request;
                    switch (request.HttpMethod.ToUpper())
                    {
                        case "GET": ProcessClientGetRequest(context); break;
                    }

                    if (response != null)
                    {
                        response.Close();
                    }
                }
                catch
                {
                    if (context != null)
                    {
                        context.Close();
                    }
                }
            }
        }

        private static void ProcessClientGetRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            Debug.Print(request.RawUrl);
            response.OutputStream.Write(outBuffer, 0, outBuffer.Length);
        }

    }
}

@ Gabo2 -

I have small code that I usually use for testing UDP on EMX - JD11
You can copy it and just run. It should work. One locate on EMX, and another on PC

EMX: Send / receive


using System;
using Microsoft.SPOT;
using System;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Security;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Net;
using Microsoft.SPOT.Net.NetworkInformation;
using GHI.Premium.Net;
using GHI.Premium.Hardware;
using GHINET = GHI.Premium.Net;

namespace Test_UDP_EMX
{
    public class Program
    {
        public static GHINET.EthernetBuiltIn ethernet_J11D;
        static InputPort button = new InputPort((Cpu.Pin)30, false, Port.ResistorMode.PullUp); // Please connect a button to pin 30, socket 8
        static OutputPort led = new OutputPort((Cpu.Pin)47, true);
        static Boolean isNetworkConfigReady = false;
        public static void Main()
        {

            while (button.Read()) 
            {
                led.Write(true);
                Thread.Sleep(50);
                led.Write(false);
                Thread.Sleep(50);
            }
            StartComunication();

        }
        static void Interface_NetworkAddressChanged(object sender, EventArgs e)
        {
            isNetworkConfigReady = false;
            Debug.Print("New address for the Network Interface ");
            Debug.Print("Is DhCp enabled: " + ethernet_J11D.NetworkInterface.IsDhcpEnabled);
            Debug.Print("Is DynamicDnsEnabled enabled: " + ethernet_J11D.NetworkInterface.IsDynamicDnsEnabled);
            Debug.Print("NetworkInterfaceType " + ethernet_J11D.NetworkInterface.NetworkInterfaceType);
            Debug.Print("Network settings:");
            Debug.Print("IP Address: " + ethernet_J11D.NetworkInterface.IPAddress);
            Debug.Print("Subnet Mask: " + ethernet_J11D.NetworkInterface.SubnetMask);
            Debug.Print("Default Gateway: " + ethernet_J11D.NetworkInterface.GatewayAddress);
            Debug.Print("Number of DNS servers:" + ethernet_J11D.NetworkInterface.DnsAddresses.Length);
            for (int i = 0; i < ethernet_J11D.NetworkInterface.DnsAddresses.Length; i++)
                Debug.Print("DNS Server " + i.ToString() + ":" + ethernet_J11D.NetworkInterface.DnsAddresses[i]);
            Debug.Print("------------------------------------------------------");
            if (ethernet_J11D.NetworkInterface.IPAddress !="0.0.0.0")
                            isNetworkConfigReady = true;

        }
        static void StartComunication()
        {          
            ethernet_J11D = new GHINET.EthernetBuiltIn();
            if (!ethernet_J11D.IsOpen)
                ethernet_J11D.Open();
            if (!ethernet_J11D.NetworkInterface.IsDhcpEnabled)
                ethernet_J11D.NetworkInterface.EnableDhcp();
            
            ethernet_J11D.NetworkAddressChanged += Interface_NetworkAddressChanged;
            GHI.Premium.Net.NetworkInterfaceExtension.AssignNetworkingStackTo(ethernet_J11D);

            while (isNetworkConfigReady == false) // wait for network is ready
            {
                Thread.Sleep(50);
            }
            System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress ip = new IPAddress(new byte[] { your PC ip });
            IPEndPoint endPoint = new IPEndPoint(ip, 2000);
            socket.Connect(endPoint);

            String msg = "Hello PC, I am FEZ spider";
            byte[] bytesToSend = Encoding.UTF8.GetBytes(msg);
            while (true)
            {
                socket.SendTo(bytesToSend, bytesToSend.Length, SocketFlags.None, endPoint);
                while (socket.Poll(2000000, SelectMode.SelectRead))
                {
                    if (socket.Available > 0)
                    {
                        byte[] inBuf = new byte[socket.Available];
                        EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        socket.ReceiveFrom(inBuf, ref recEndPoint);
                        if (!recEndPoint.Equals(endPoint))// Check if the received packet is from the 192.168.0.2
                            continue;
                        Debug.Print(new String(Encoding.UTF8.GetChars(inBuf)));
                    }
                }
                Thread.Sleep(100);
            }
        }
    }
}





On PC: Send /receive


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Test_UDP_PC
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint MyServiceEndPoint = new IPEndPoint(IPAddress.Any, 2000);
            mySocket.Bind(MyServiceEndPoint);
            while (true)
            {
                while (mySocket.Poll(200000, SelectMode.SelectRead))
                {
                    if (mySocket.Available > 0)
                    {
                        byte[] inBuf = new byte[mySocket.Available];
                        EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        mySocket.ReceiveFrom(inBuf, ref recEndPoint);
                        Console.WriteLine("Message From " + ((IPEndPoint)recEndPoint).Address.ToString());
                        Console.WriteLine(new string(Encoding.UTF8.GetChars(inBuf)));
                        String msg = "Hello FEZ Spider! I am PC";
                        byte[] bytesToSend = Encoding.UTF8.GetBytes(msg);
                        mySocket.SendTo(bytesToSend, bytesToSend.Length, SocketFlags.None,
                        (IPEndPoint)recEndPoint);
                    }
                }
            }
        }
    }
}

Could you also provide details on how your network is setup for the connection between the PC and the Spider?

Dat, I’ll make the test with your example code.

James, the configuration of the network is:

PC:

Static IP 192.168.1.10
Mask: 255.255.255.0
Gateway: 192.168.1.1

FEZ Spider

Static IP 192.168.1.9
Mask: 255.255.255.0
Gateway: 192.168.1.1

Im’ using a cross cable to connect the PC and the FEZ Spider.

thanks.

@ Gabo2 -

oh, I don’t think cross cable work with that code.
I am using a switch

Dat, the code of the spider was right (with static IP), what did not work was the udp server on the PC, your code helped me a lot.

Thank you very much to all for your help.