1. 程式人生 > 其它 >TCP伺服器的建立過程

TCP伺服器的建立過程

TCP伺服器(單客戶端)

1. 獲取本地主機的IP和埠號

若本地主機有多個IP地址,則需要獲取本地主機所有IP地址,指定某個IP地址用於建立伺服器。

	char **addresses = NULL;
	char addr_arr[10][20] = {0};
	int numAddresses;
	GetAllTCPHostAddresses (&addresses, &numAddresses);
	/* Use the address strings... */
	for (int index = 0; index < numAddresses; index++)
	{
		strcpy (addr_arr [index], addresses [index]);  //copy all address to array
		TCPFreeMemory (addresses[index]);  //Free address string
	}
	TCPFreeMemory (addresses);  //Free addresses array

2. 註冊TCP伺服器

有了IP埠號,就可以註冊TCP伺服器。

if (RegisterTCPServerEx (portNum, ServerTCPCB, 0, ip_address) < 0)
	{
		MessagePopup("TCP Server", "Server registration failed!");
	}

ServerTCPCB指向處理客戶端請求的同步回撥函式的指標。

3. TCP伺服器和客戶端的通訊

/* tcp伺服器回撥函式原型 */
int (*tcpFuncPtr) (unsigned handle, int xType, int errCode, void *callbackData);
//unsigned handle :控制代碼 ???
//int xType :接收事件型別(TCP_CONNECT、TCP_DISCONNECT、TCP_DATAREADY)
//int errCode:用於判斷TCP_DISCONNECT的原因

tcp伺服器回撥函式的呼叫

int CVICALLBACK ServerTCPCB (unsigned handle, int event, int error,void *callbackData)
{
	char receiveBuf[256] = {0};  
	int dataSize = sizeof (receiveBuf) - 1;  //Receive max size is 255 Byte
	char addrBuf[31];
	switch (event)
		{
		case TCP_CONNECT:
			if (g_hconversation)
				{
				/* We already have one client, don't accept another... */
                ;
				tcpChk (DisconnectTCPClient (handle));
				}
			else
				{
				/* Handle this new client connection */
				g_hconversation = handle;
                ;
				/* Set the disconect mode so we do not need to terminate connections ourselves. */
				tcpChk (SetTCPDisconnectMode (g_hconversation, TCP_DISCONNECT_AUTO));
				}
			break;
		case TCP_DATAREADY:
			if ((dataSize = ServerTCPRead (g_hconversation, receiveBuf, dataSize, 1000)) < 0)
				{
				;
				}
			else
				{
				receiveBuf[dataSize] = '\0';
				;
				}
			break;
		case TCP_DISCONNECT:
			if (handle == g_hconversation)
				{
				/* The client we were talking to has disconnected... */
				g_hconversation = 0;
                ;
				/* Note that we do not need to do any more because we set the disconnect mode to AUTO. */
				}
			break;
	}
Done:    
	return 0;
}