服务器:
SOCKET s; s = ::socket(AF_INET,SOCK_STREAM,0); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(75); addr.sin_addr.S_un.S_addr = INADDR_ANY; ::bind(s,(sockaddr*)&addr,sizeof(addr)); ::listen(s,5); SOCKET s2; sockaddr_in addr2; int n = sizeof(addr2); s2 = ::accept(s,(sockaddr*)&addr2,&n); char sztext[20] = {0}; ::recv(s2,sztext,sizeof(sztext),0); ::closesocket(s2); ::closesocket(s);
客户端:
SOCKET s; s = ::socket(AF_INET,SOCK_STREAM,0); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(75); addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); ::connect(s,(sockaddr*)&addr,sizeof(addr)); char sztext[] = _T("你好"); ::send(s,sztext,sizeof(sztext),0); ::closesocket(s);
TCP的保活机制:由于TCP一端可能意外而断开连接,这时候另一端如何知道对面是否还在连接呢。
1、自己写一个心跳程序,定时去向通信对方发送信息并得到反馈。
2、使用自带的保活函数。以下是windows的保活函数使用。
#include <mstcpip.h> BOOL SetTcpKeepAlive(int fd, int start, int interval) { // 开启KeepAlive BOOL bKeepAlive = TRUE; int nRet = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&bKeepAlive, sizeof(bKeepAlive)); if (nRet == SOCKET_ERROR) { return FALSE; } // 设置KeepAlive参数 tcp_keepalive alive_in = {0}; tcp_keepalive alive_out = {0}; alive_in.keepalivetime = start; // 开始首次KeepAlive探测前的TCP空闭时间 alive_in.keepaliveinterval = interval; // 两次KeepAlive探测间的时间间隔 alive_in.onoff = bKeepAlive; unsigned long ulBytesReturn = 0; nRet = WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive_in, sizeof(alive_in), &alive_out, sizeof(alive_out), &ulBytesReturn, NULL, NULL); if (nRet == SOCKET_ERROR) { return FALSE; } return TRUE; }