Main Site Documentation

Gadgeteer TCP-Connection


#1

Hi,

Sombody can help my to fix my code?

using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Presentation.Shapes;
using Microsoft.SPOT.Touch;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using GHI.Premium.Net;

namespace GadgeteerTCP
{
public partial class Program
{
private string dottedServerIPAddress = “127.0.0.1”;
private const int port = 8080;

    private Socket clientSocket;
    private byte[] messageBytes;
    // This method is run when the mainboard is powered up or reset.   
    void ProgramStarted()
    {
        ethernet_J11D.DebugPrintEnabled = true;
        ethernet_J11D.UseDHCP();
        ethernet_J11D.UseThisNetworkInterface();

        ethernet_J11D.NetworkUp += new GTM.Module.NetworkModule.NetworkEventHandler(ethernet_NetworkUp);


    }

    void ethernet_NetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
    {
        initethernetConnection();

    }



    void initethernetConnection()
    {
        Debug.Print("connecting to Ethernet ");
        if (ethernet_J11D.Interface.IsOpen)
        {
            Debug.Print("interface was open");
        }
        else
        {
            Debug.Print("interface was not open");
            ethernet_J11D.Interface.Open();
        }

        ethernet_J11D.Interface.CableConnectivityChanged += new EthernetBuiltIn.CableConnectivityChangedEventHandler((s, e) =>
            {
                Debug.Print("Ethernet conn changed!");
                if (e.IsConnected) { Debug.Print("ETHERNET connected!"); }
                else { Debug.Print("Ethernet  disconnected.."); }
            });



        var settings = ethernet_J11D.NetworkSettings;

        Debug.Print("------------------------------------------------");
        //Debug.Print("MAC: " + ByteExten.ToHexString(settings.PhysicalAddress, "-"));
        Debug.Print("IP Address:   " + settings.IPAddress);
        Debug.Print("DHCP Enabled: " + settings.IsDhcpEnabled);
        Debug.Print("Subnet Mask:  " + settings.SubnetMask);
        Debug.Print("Gateway:      " + settings.GatewayAddress);
        Debug.Print("------------------------------------------------");


        dottedServerIPAddress = settings.IPAddress;
        using (clientSocket = new Socket(AddressFamily.InterNetwork,
                                                       SocketType.Stream,
                                                       ProtocolType.Tcp))
        {
            IPEndPoint RemoteHost = new IPEndPoint(Dns.GetHostEntry(dottedServerIPAddress).AddressList[0], port);
            clientSocket.Connect(RemoteHost);

        messageBytes = Encoding.UTF8.GetBytes("Hello World!");
        clientSocket.Send(messageBytes);
        byte[] inBuffer = new byte[100];
        int count = clientSocket.Receive(inBuffer);
        char[] chars = Encoding.UTF8.GetChars(inBuffer);
        string str = new string(chars, 0, count);
        Debug.Print(str);

        }
        

        


    }
}

}

I get this error :

Exception System.Net.Sockets.SocketException - CLR_E_FAIL (1)

#### Message: 
#### Microsoft.SPOT.Net.SocketNative::connect [IP: 0000] ####
#### System.Net.Sockets.Socket::Connect [IP: 001d] ####
#### GadgeteerTCP.Program::initethernetConnection [IP: 00e2] ####
#### GadgeteerTCP.Program::ethernet_NetworkUp [IP: 0005] ####
#### Gadgeteer.Modules.Module+NetworkModule::OnNetworkEvent [IP: 004d] ####
#### System.Reflection.MethodBase::Invoke [IP: 0000] ####
#### Gadgeteer.Program::DoOperation [IP: 001a] ####
#### Microsoft.SPOT.Dispatcher::PushFrameImpl [IP: 0054] ####
#### Microsoft.SPOT.Dispatcher::PushFrame [IP: 001a] ####
#### Microsoft.SPOT.Dispatcher::Run [IP: 0006] ####
#### Gadgeteer.Program::Run [IP: 0020] ####
#### SocketException ErrorCode = 10054
#### SocketException ErrorCode = 10054

A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10054
#### SocketException ErrorCode = 10054
Error invoking method “Gadgeteer.Modules.Module+NetworkModule” (check arguments to Program.BeginInvoke are correct)


#2

@ sam_simsim - The 10054 error code usually indicates that the remote host closed the connection. Are you sure that the server is functioning properly?


#3

Hi John,

I have an node.js server. I have tesed the server and it works with a node.js and netmf client but only on gadgeteer i get this error :(.

the code for the server:

var net = require(‘net’);

var PORT = 8080;

net.createServer(function(sock) {

console.log('CONNECTED: ' + ':'+ sock.remotePort);


sock.on('data', function(data) {
    
    console.log('DATA ' +  ': ' + data);

    // Write the data back to the socket, the client will receive it as data from the server
    sock.write('You said "' + data + '"');

    
});

}).listen(PORT);

console.log('Server listening on ’ + ‘:’+ PORT);


#4

@ sam_simsim - Can you try to connect to other servers and see if the issue remains? Can you use wireshark to see if what the device is sending and receiving?


#5

@ sam_simsim - Welcome to the forum.

Just want to point out that we have code formatting in the forum posts. This will make you post so much better. It is a button with ‘101010’ icon. You can always go back to your published message and edit it.


#6

I wrote three servers but all in node.js do you mean another platform ? which one ? I never used wireshark can you please guide me ? :-[


#7

I tried to connect my gadgeteer to a netmf server on C#. I get the same error. I tried to connect the server with netmf client and it worked perfectly. :wall:


#8

Hi,

Looking at your code, aren’t you trying to connect to your own embedded device? I think thats the reason for the socket error you’re receiving.


#9

Hi Patrick,

where you see that? I run same code on netmf and it’s working fine.

        private const string dottedServerIPAddress = "127.0.0.1";
        private const int port =8080;
       
        public static void Main()
          {

             

            using (Socket clientSocket = new Socket(AddressFamily.InterNetwork,
                                                            SocketType.Stream,
                                                            ProtocolType.Tcp))
                {
                    // Addressing
                    IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress);
                    IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port);
                
                    // Connecting
                    Debug.Print("Connecting to server " + serverEndPoint + ".");
                
                    clientSocket.Connect(serverEndPoint);
                    Debug.Print("Connected to server.");

                    // Sending
                    
                        byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!");
                        clientSocket.Send(messageBytes);

                        byte[] inBuffer = new byte[100];
                        int count = clientSocket.Receive(inBuffer);
                        char[] chars = Encoding.UTF8.GetChars(inBuffer);
                        string str = new string(chars, 0, count);
                      
                    
                }// the socket will be closed here
             }
    }
   

} 

#10

Sam, can you edit your posts and fix up the code tags ?

He sees this line in your code:


that means it'll attempt to connect to itself.

#11

Change the IPAddress (and Port) in that line to the server running the socket listener and it should be fine.


#12

Hi Brett,

I chaged the code like this:

public partial class Program
{
private string dottedServerIPAddress = “127.0.0.1”;
private const int port = 8080;

    private Socket clientSocket;
    private byte[] messageBytes;
    // This method is run when the mainboard is powered up or reset.   
    void ProgramStarted()
    {
        ethernet_J11D.DebugPrintEnabled = true;
        ethernet_J11D.UseDHCP();
        ethernet_J11D.UseThisNetworkInterface();

        ethernet_J11D.NetworkUp += new GTM.Module.NetworkModule.NetworkEventHandler(ethernet_NetworkUp);


    }

    void ethernet_NetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
    {
        
        using (clientSocket = new Socket(AddressFamily.InterNetwork,
                                                       SocketType.Stream,
                                                       ProtocolType.Tcp))
        {
            IPEndPoint RemoteHost = new IPEndPoint(Dns.GetHostEntry(dottedServerIPAddress).AddressList[0], port);
            clientSocket.Connect(RemoteHost);

        messageBytes = Encoding.UTF8.GetBytes("Hello World!");
        clientSocket.Send(messageBytes);
        byte[] inBuffer = new byte[100];
        int count = clientSocket.Receive(inBuffer);
        char[] chars = Encoding.UTF8.GetChars(inBuffer);
        string str = new string(chars, 0, count);
        Debug.Print(str);

        }

    }
     
}

}

but i still get same error and if i change the IP Address to 192.168.xx it’s just hangs.


#13

Within Visual Studio place a breakpoint at the line below and look at the value of Remote Host.


#14

The value is {127.0.0.1:8080}.

the server have same IP and Port. :confused:


#15

Sam, just for the record: you are aware of the fact that 127.0.0.1 is a local loopback address and it is used to test communication on same local device?

You must replace the 127.0.0.1 ip address with the ip address of your device which is listening for incoming sockets. Start debugging from there


#16

I’m just confused because first you say if i use dottedServerIPAddress = settings.IPAddress; so it’s mean that i want to connect to my own device then you say i need to have the IP-adress for the device ? the method settings.IPAdress generate the IP-addess for the device and it’s generate 192.168.1.5 for this time.


#17

I have now the value like this {192.168.1.5:8080}, and the node.js server listening on port 8080. but i have the same error:

#### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (5) ####
#### Message: 
#### Microsoft.SPOT.Net.SocketNative::connect [IP: 0000] ####
#### System.Net.Sockets.Socket::Connect [IP: 001d] ####
#### GadgeteerTCP.Program::Interface_NetworkAddressChanged [IP: 0076] ####
#### GHI.Premium.Net.NetworkInterfaceExtension::NetworkChangeExtension_NetworkAddressChanged [IP: 0021] ####
#### GHI.Premium.Net.NetworkChangeExtension::OnNetworkChangeCallback [IP: 00ac] ####
#### GHI.Premium.Net.NetworkChangeExtension+NetworkChangeExtensionListener::OnEvent [IP: 000d] ####
#### Microsoft.SPOT.EventSink::EventDispatchCallback [IP: 0014] ####
#### SocketException ErrorCode = 10054
#### SocketException ErrorCode = 10054

A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10054
An unhandled exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll


#18

Sam, sorry for the confusion :slight_smile: it is not my intention!

Let me try to get things clear

Your remote device is running the socket server (receive application) to which you want to connect from your netmf device, right? Suppose your remote device is having ip address 192.168.1.100 and your netmf is having 192.168.1.5 as ip address.

So in your software you must use 192.168.1.100 (the address of your node.js server) as your ip endpoint.

Edit:

The error you’re getting is because your netmf tries to connect to a socket on your own netmf device which isn’t listening.


#19

Thank you Patrick :). I will try that. :slight_smile:


#20

Patrick I have two services now but both works on localhost :/. I don’t know how to make them to work for my gadgeteer. They just listning on port and any IP- address who want to connect with the server. I tried to listen on 192.168.1.5 wich is the gadgeteer IP-address, but the node.js server does not want to work and gave me an error. but it works fine if it’s listning on 127.0.0.1(localhost). the other one is a netmf server and it listen on any socket too listeningSocket.Bind(new IPEndPoint(IPAddress.Any, port)), and when I try to write listeningSocket.Bind(new IPEndPoint(Dns.GetHostEntry(dottedServerIPAddress).AddressList[0], port)) it gives my an error :/.

node.js server:

var net = require(‘net’);

var HOST = ‘127.0.0.1’;
var PORT = 8080;

var client = new net.Socket();
client.connect(PORT, HOST, function() {

console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
client.write('I am Chuck Norris!');

});

// Add a ‘data’ event handler for the client socket
// data is what the server sent to this socket
client.on(‘data’, function(data) {

console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();

});

// Add a ‘close’ event handler for the client socket
client.on(‘close’, function() {
console.log(‘Connection closed’);
});

netmf server:


   public class Program
        {
            private const int port = 8080;
            public static void Main()
            {

            using (Socket listeningSocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream,
                        ProtocolType.Tcp))
             {
                     listeningSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                     Debug.Print("Listening for a client...");
                    listeningSocket.Listen(1);
            using (Socket communicationSocket = listeningSocket.Accept())
            {
                Debug.Print("Connected to client.");
                //wait infinitely to get a response
                communicationSocket.ReceiveTimeout = -1;
                byte[] inBuffer = new byte[1000];
                int count = communicationSocket.Receive(inBuffer);
                string message = new string(Encoding.UTF8.GetChars(inBuffer));
                Debug.Print("Received '" + message + "'.");
              }
             }
        }
    }
}