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;
}
标签:index,handle,addresses,int,TCP,Server,hconversation
From: https://www.cnblogs.com/caojun97/p/16740874.html