6.4.4 UDP Server Example Code

SOCKET	serverSocketHdl;
uint8	rxBuffer[256];

/* Socket event handler.*/	
void udpServerSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
	if(u8Msg == SOCKET_MSG_BIND)
	{
		tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
		if(pstrBind->status == 0)
		{
			// call Recv
			recvfrom(serverSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
		}
		else
		{
			printf("Bind Failed\n");
		}
	}
	else if(u8Msg == SOCKET_MSG_RECV)
	{
		tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
		if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
		{
			// Perform data exchange.
			uint8	acSendBuffer[256];
			uint16	u16MsgSize;
	
			// Fill in the acSendBuffer with some data
	
			// Send some data to the same address.
			sendto(acceptedSocketHdl, acSendBuffer, u16MsgSize, 0,
				pstrRecvMsg-> strRemoteAddr, sizeof(pstrRecvMsg-> strRemoteAddr));
		
			// call Recv
			recvfrom(serverSocketHdl, rxBuffer, sizeof(rxBuffer), 0);

			// Close the socket when finished.
			close(serverSocketHdl);
		}
	}
}

/* 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 udpStartServer(uint16 u16ServerPort)
{
	struct sockaddr_in		strAddr;
	// Initialize the socket layer.
	socketInit();
	
	// Register socket application callbacks.
	registerSocketCallback(udpServerSocketEventHandler, NULL);
	// Create the server listen socket.
	listenSocketHdl = socket(AF_INET, SOCK_DGRAM, 0);
	if(listenSocketHdl >= 0)
	{
		strAddr.sin_family		= AF_INET;
		strAddr.sin_port		= _htons(u16ServerPort);
		strAddr.sin_addr.s_addr 	= 0; //INADDR_ANY
		bind(serverSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
	}
}