SOCKET clientSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler. */
void tcpClientSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
if(sock == clientSocketHdl)
{
if(u8Msg == SOCKET_MSG_CONNECT)
{
// Connect Event Handler.
tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
if(pstrConnect->s8Error == 0)
{
// Perform data exchange.
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// send data
send(clientSocketHdl, acSendBuffer, u16MsgSize, 0);
// Recv response from server.
recv(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
}
else
{
printf("TCP Connection Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
{
// Process the received message.
// Close the socket.
close(clientSocketHdl);
}
}
}
}
// This is the DNS callback. The response of gethostbyname is here.
void dnsResolveCallback(uint8* pu8HostName, uint32 u32ServerIP)
{
struct sockaddr_in strAddr;
if(u32ServerIP != 0)
{
clientSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags);
if(clientSocketHdl >= 0)
{
strAddr.sin_family = AF_INET;
strAddr.sin_port = _htons(443);
strAddr.sin_addr.s_addr = u32ServerIP;
connect(clientSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
}
}
else
{
printf("DNS Resolution Failed\n");
}
}
/* This function needs to be called from main function. For the callbacks to be invoked correctly, the API m2m_wifi_handle_events must be called continuously from main. */
void tcpConnect(char *pcServerURL)
{
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback(tcpClientSocketEventHandler, dnsResolveCallback);
// Resolve Server URL.
gethostbyname((uint8*)pcServerURL);
}