6.4.2 TCP Server Example Code

SOCKET	listenSocketHdl, acceptedSocketHdl;
uint8		rxBuffer[256];
uint8		bIsfinished = 0;

/* Socket event handler. */	
void tcpServerSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
	if(u8Msg == SOCKET_MSG_BIND)
	{
		tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
		if(pstrBind->status == 0)
		{
			listen(listenSocketHdl, 0); 
		}
		else
		{
			printf("Bind Failed\n");
		}
	}
	else if(u8Msg == SOCKET_MSG_LISTEN)
	{
		tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg;
		if(pstrListen->status != 0)
		{
			printf("listen Failed\n");
		}
	}	
	else if(u8Msg == SOCKET_MSG_ACCEPT)
	{
		// New Socket is accepted.
		tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg;
		if(pstrAccept->sock >= 0)
		{
			// Get the accepted socket.
			acceptedSocketHdl = pstrAccept->sock;

			recv(acceptedSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
		}
		else
		{
			printf("Accept Failed\n");
		}
	}
	else if(u8Msg == SOCKET_MSG_RECV)
	{
		tstrSocketRecvMsg	*pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
		if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
		{
			// Process the received message
			// Perform data exchange

			uint8	acSendBuffer[256];
			uint16	u16MsgSize;
	
			// Fill in the acSendBuffer with some data here
	
			// Send some data.
			send(acceptedSocketHdl, acSendBuffer, u16MsgSize, 0);
		
			// Recv response from client.
			recv(acceptedSocketHdl, rxBuffer, sizeof(rxBuffer), 0);

			// Close the socket when finished.
			if(bIsfinished)
			{
				close(acceptedSocketHdl);
				close(listenSocketHdl);
			}
		}
	}
}

/* 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 tcpStartServer(uint16 u16ServerPort)
{
	struct sockaddr_in		strAddr;

	// Initialize the socket layer.
	socketInit();
	
	// Register socket application callbacks.
	registerSocketCallback(tcpServerSocketEventHandler, NULL);
	
	// Create the server listen socket.
	listenSocketHdl = socket(AF_INET, SOCK_STREAM, 0);
	if(listenSocketHdl >= 0)
	{
		strAddr.sin_family		= AF_INET;
		strAddr.sin_port		= _htons(u16ServerPort);
		strAddr.sin_addr.s_addr 	= 0; //INADDR_ANY
		bind(listenSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
	}
}