7.5 SSL Client Code Example

SOCKET	sslSocketHdl;
uint8	rxBuffer[256];

/* Socket event handler. */	
void SSL_SocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
	if(sock == sslSocketHdl)
	{
	if(u8Msg == SOCKET_MSG_CONNECT)
		{
		// Connect event
			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 some data.
				send(sock, acSendBuffer, u16MsgSize, 0);
		
				// Recv response from server.
				recv(sslSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
			}
			else
			{
				printf("SSL Connection Failed\n");
			}
		}
		else if(u8Msg == SOCKET_MSG_RECV)
		{
			tstrSocketRecvMsg	*pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
			if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
			{
				// Process the received message here
			
				// Close the socket if finished.
				close(sslSocketHdl);
			}
		}
	}
}

/* This is the DNS callback. The response of gethostbyname is here. */
void dnsResolveCallback(uint8* pu8HostName, uint32 u32ServerIP)
{
	struct sockaddr_in	strAddr;

	if(u32ServerIP != 0)
	{
		sslSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags);
		if(sslSocketHdl >= 0)

		{
			strAddr.sin_family	= AF_INET;
			strAddr.sin_port		= _htons(443);
			strAddr.sin_addr.s_addr 	= u32ServerIP;
			connect(sslSocketHdl, (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 SSL_Connect(char *pcServerURL)
{
	// Initialize the socket layer.
	socketInit();
	
	// Register socket application callbacks.
	registerSocketCallback(SSL_SocketEventHandler, dnsResolveCallback);

	// Resolve Server URL.
	gethostbyname((uint8*)pcServerURL);	
}