socket 客户端长连接(C++)

#include "stdafx.h"
#include 
#include 
#include   
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main(int argc, char* argv[])
{
	const int BUF_SIZE = 64;	
	WSADATA wsd; //WSADATA变量
	SOCKET sHost; //服务器套接字
	SOCKADDR_IN servAddr; //服务器地址
	char buf[]="123456\n"; //接收数据缓冲区
	char bufRecv[BUF_SIZE];
	int retVal; //返回值
	//初始化套结字动态库
	if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
	{
		cout << "WSAStartup failed!" << endl;
		return -1;
	}
	//创建套接字
	sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(INVALID_SOCKET == sHost)
	{
		cout << "socket failed!" << endl;
		WSACleanup();//释放套接字资源
		return  -1;
	}	
	//设置服务器地址
	servAddr.sin_family =AF_INET;
	servAddr.sin_addr.s_addr = inet_addr("192.168.45.136");
	servAddr.sin_port = htons(666);
	int nServAddlen  = sizeof(servAddr);
	
	//连接服务器
	retVal=connect(sHost,(LPSOCKADDR)&servAddr, sizeof(servAddr));
	if(SOCKET_ERROR == retVal)
	{
		cout << "connect failed!" << endl;
		closesocket(sHost); //关闭套接字
		WSACleanup(); //释放套接字资源
		return -1;
	}
	fd_set	wfds, rfds, efds;
	timeval tv;
	tv.tv_sec = 10;
	tv.tv_usec = 500;
	int count =-1;
	while(true)
	{
		FD_ZERO(&wfds);
		FD_ZERO(&rfds);
		FD_ZERO(&efds);
		FD_SET(sHost,&wfds);
		FD_SET(sHost,&rfds);
		FD_SET(sHost,&efds);		
		int Rtn = select(FD_SETSIZE,&rfds,&wfds,&efds,&tv);
		if (Rtn>0)
		{
			if(FD_ISSET(sHost,&rfds)>0)//表示有读的
			{
				count = recv(sHost, bufRecv,BUF_SIZE , 0);
			}
			if (FD_ISSET(sHost,&wfds)>0)//表示可以写
			{
				if (count>0)
				{
					retVal = send(sHost, buf, strlen(buf), 0);
					if (SOCKET_ERROR == retVal)
					{
						cout << "send failed!" << endl;
						closesocket(sHost); //关闭套接字
						WSACleanup(); //释放套接字资源
						return -1;
					}
					count = -1;
				}			
			}
			if (FD_ISSET(sHost,&efds)>0)//表示有异常
			{
			}
		}
		else
		{
			cout << "error1";
		}
	}
	//退出
	closesocket(sHost); //关闭套接字
	WSACleanup(); //释放套接字资源
	printf("Hello World!\n");
	return 0;
}

你可能感兴趣的:(socket 客户端长连接(C++))