Examples‎ > ‎

Simple Socket

With this example, we are going to create a client TCP socket and to send the "Hi there" string.
 
USHORT usMyPort = 0;
IPADDRESS ipMyAddress = 0;
E_SOCKET* pSocket = eSocketCreate(E_SOCKET_STREAM, usMyPort, ipMyAddress, SocketStatusCallback, SocketReceiveCallback);
if (pSocket!=NULL)
{
    USHORT usDestinationPort = 23;
    IPADDRESS ipDestination;
    StringToIp("192.168.0.7", &ipDestination);
    if (eSocketConnect(pSocket, ipDestination, usDestinationPort)!=E_OK)
    {
        // We are going to send the information on socket connection.
    }
}

In the socket creation, we must provide two callback functions. So, we don't need to create task to perform simple tasks. For complex processes, we ae going to need to create a task, and send the events from the callback function to the task. Please read the eSockets User Manual to see an example of an advanced IP server.

In the following source code you will find an example of the callback functions.

VOID SocketStatusCallback(E_SOCKET *pSocket, E_SOCKET_STATUS eNewStatus)
{
STRING strMyName = "Jordi";

switch (eNewStatus)
{
case E_SOCKET_CLOSED:
// The connection failed
break;

case E_SOCKET_ESTABLISHED:
eSocketPrintf(pSocket, "Hi there %s", strMyName);
break;
default:
break;
}
}

You see that we are using a complex eSocketPrintf function in order to generate the information to be sent throught the socket. This is possible because this function is optimized and it is generationg the information directly over the packets that are going to be sent to the Ethernet driver.

VOID SocketReceiveCallback(E_SOCKET *pSocket, E_PACKET *pPacket, UCHAR* pData, USHORT nDatalen)
{
     // In this case, nothing to do with the information
    eSocketFreePacket(pSocket, pPacket);
}

The information that is coming from the network is delivered to the callback function with no copy anywhere. So, you must free the packet to let the network to accept more information.


Comments