11 years, 1 month ago.

looking for a simple TCP socket

hi there,

im a beginner in C programming.

Have somebody a example program for a simple TCP Socket server?

i bought the NET IO App in Android Play store.

The App comunicate with the mbed over the ethernet, but the App need a TCP socket.

my idea is a simple Code

if(incoming_data=="set somthing on") { do_something(); }

for switch a digital output.

Can somebody help me ?

thanks you very much!!!

I have a setup that does just that. I opted for the mbed to be a client which connects to a windows based server. This gives scalability if your mbed network gets bigger. The issues I've run into is not with the TCP data transfer, but the parsing of text messages. It takes quite some thinking to get it right. You should decide on an 'end of transfer' string that either side can detect and act on. Furthermore the sending side needs to know if the message has been received - and received correctly, and if not, what to do.

Request a resend? To what client? How long to wait? Should I buffer later data while waiting for the resend? Do I need transfer ID's? The list goes on.

Of course this depends on your intended application and how important every transaction is.

I rely on the old EthernetNetIf library which is known for low transfer rate but high reliability. The newfangled ethernet libraries can achieve transfer rates hundreds or thousands of times faster, but I've read reports of it crashing at the least wanted point, so for my specific app I'm sticking with the old one. At least until the higher rates are required.

These are excerpts from my heavily reduced working code:

#include "EthernetNetIf.h"
#include "TCPSocket.h"

EthernetNetIf eth; // If you want DHCP address allocation (make reservations at the DHCP server)

/*
EthernetNetIf eth(               // If you use static IP
    IpAddr(192,168,0,123),  // IP Address
    IpAddr(255,255,255,0),  // Network Mask
    IpAddr(192,168,0,1),      // Gateway [probably your router]
    IpAddr(192,168,0,1)       // DNS     [probably your router]
);
*/

TCPSocket TCP;
TCPSocketErr TCPerr;
IpAddr MyIP;

int SendServer(char *Msg)
{
    char str[128];
    int n=sprintf(str,"%03d%05d%s\n",Id,Seq,Msg); // Adding mbed ID and transmission sequence number.
    TCP.send(str,strlen(str));
    Seq++;
    return(0);
}

void ConnectServer()
{
    TCP.close(); //Just in case...
    pc.printf("Connecting to server %d.%d.%d.%d:%d\n",MyIP[0],MyIP[1],MyIP[2],SERVER_IP,SERVER_PORT);
    Host Srv(IpAddr(MyIP[0],MyIP[1],MyIP[2],SERVER_IP), SERVER_PORT); // Connect to this server.
    // SERVER_IP is the last octet in the servers IP address. SERVER_PORT is the listening port of the server.
    TCPerr=TCP.connect(Srv);
    if (TCPerr != TCPSOCKET_OK) {
        pc.printf("Socket connection error [Err %d]\n",TCPerr);
        Connected=0;
    }    else {
        pc.printf("Connected to server  %d.%d.%d.%d:%d [%d]\n",MyIP[0],MyIP[1],MyIP[2],SERVER_IP,SERVER_PORT,TCPerr);
        Connected=1;
    }
}

void onTCPSocketEvent(TCPSocketEvent e)
{
    int len;
    switch (e) {
        case TCPSOCKET_ACCEPT:
            pc.printf("TCP Socket Accepted\n");
            break;
        case TCPSOCKET_CONNECTED:
            pc.printf("TCP Socket Connected\n");
            Connected=1;
            break;
        case TCPSOCKET_WRITEABLE:
            break;

        case TCPSOCKET_READABLE:  // Happens when inbound data is available.
            char buf[128];
            len=1; // Init value
            while (len) { // Continue as long as there's something in the buffer.
                len = TCP.recv(buf, 128);
                buf[len]=0; // Terminate string

		// Here's where you parse incoming data.

            break;

        case TCPSOCKET_CONTIMEOUT:
            pc.printf("TCP Socket Timeout\n");
            Connected=0;
            break;
        case TCPSOCKET_CONRST:
            pc.printf("TCP Socket CONRST\n");
            Connected=0;
            //ConnectServer();
            break;
        case TCPSOCKET_CONABRT:
            pc.printf("TCP Socket CONABRT\n");
            Connected=0;
            break;
        case TCPSOCKET_ERROR:
            pc.printf("TCP Socket Error\n");
            Connected=0;
            break;
        case TCPSOCKET_DISCONNECTED:
            //Close socket...
            TCPerr=TCP.close();
            pc.printf("TCP Socket Disconnected %d\n",TCPerr);
            Connected=0;
            break;
        default:
            pc.printf("DEFAULT\n");
    }
}

int SetupEth()
{
    pc.printf("\nSetting up ethernet...\n");
    EthernetErr ethErr = eth.setup();
    if (ethErr) {
        pc.printf("Error (ethernet) %d in setup.\n", ethErr);
        return -1;
    } else {
        MyIP = eth.getIp();
        pc.printf("mbed IP Address: %d.%d.%d.%d\n", MyIP[0], MyIP[1], MyIP[2], MyIP[3]);

        TCP.setOnEvent(&onTCPSocketEvent); // Catch ethernet events
        ConnectServer();
        return 0;
    }
}

int main() {
    SetupEth();
    while (1) {
        Net::poll();
	// *** Your thing here***
        wait_ms(10);
    }
} 
posted by Hugo Harming 30 Oct 2013

Sort of a double post :/

posted by Hugo Harming 30 Oct 2013

1 Answer

11 years, 1 month ago.

The TCPSocketServer page is very useful:

http://mbed.org/handbook/Socket

Modify the TCP Echo server to do something when you receive data, rather than echoing it back.