1. create socket
struct sockaddr_in addr;
addr.sin_family = AF_INET;
// Server address
addr.sin_addr.s_addr = inet_addr(host);
// Server port
addr.sin_port = htons(port);
// Creating socket
if ((soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
throw connector_exception("connector: can't create socket");
2. connect
if (::connect(soc, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR)
throw connector_exception("connector: can't connect.");
3. 设置为非阻塞式socket
unsigned long ul = 1;
int ret = ioctlsocket(rec(), FIONBIO, (unsigned long*)&ul);
if(ret==SOCKET_ERROR)
log <<"ioctlsocket error" << endl;
4. select socket
FD_SET(rec(), &r_readfds); FD_SET(rec(), &r_exfds);
if ((iret=select(0,&r_readfds, NULL,&r_exfds,&tv))==SOCKET_ERROR){
每次调用好select后,select 函数自动把r_readfds,r_exfds都设为空,必须重新调用
FD_SET(rec(), &r_readfds); FD_SET(rec(), &r_exfds); 否则会报10022 WSAEINVAL 错误
5 参考文献