Connect()
BOOL Connect( LPCTSTR lpszHostAddress, UINT nHostPort); BOOL Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen);
第一种方式:(IP地址为服务器IP地址:lpszHostAddress,端口为服务器Socket的端口:nHostPort)
客户端Socket调用Connect()之后,触发OnConnect()虚函数,向服务器端Socket申请连接。
参数:
lpszHostAddress
此对象与套接字的网络地址:一个计算机名称(例如“ftp.microsoft.com”或一个虚线的数字(如“128.56.22.8”。
nHostPort
标识套接字应用程序的端口。
lpSockAddr
对包含连接的套接字地址的 SOCKADDR 结构的指针。
nSockAddrLen
地址的长度。lpSockAddr 的以字节为单位)。
返回值:
成功则返回0,失败返回-1,错误原因存于errno中。对连接错误的处理,一般在OnConnect()中处理。
错误代码:
EBADF 参数sockfd 非合法socket处理代码
EFAULT 参数serv_addr指针指向无法存取的内存空间
ENOTSOCK 参数sockfd为一文件描述词,非socket。
EISCONN 参数sockfd的socket已是连线状态
ECONNREFUSED 连线要求被server端拒绝。
ETIMEDOUT 企图连线的操作超过限定时间仍未有响应。
ENETUNREACH 无法传送数据包至指定的主机。
EAFNOSUPPORT sockaddr结构的sa_family不正确。
EALREADY socket为不可阻塞且先前的连线操作还未完成。
void CMyAsyncSocket::OnConnect(int nErrorCode) // CMyAsyncSocket is // derived from CAsyncSocket {
//连接失败程序处理: if (0 != nErrorCode) { switch(nErrorCode) { case WSAEADDRINUSE: AfxMessageBox(_T("The specified address is already in use.指定的地址已在使用中\n")); break; case WSAEADDRNOTAVAIL: AfxMessageBox(_T("The specified address is not available from ") _T("the local machine.指定的地址不可用本地机器\n")); break; case WSAEAFNOSUPPORT: AfxMessageBox(_T("Addresses in the specified family cannot be ") _T("used with this socket.在指定的家庭中地址不能使用这个套接字。\n")); break; case WSAECONNREFUSED: AfxMessageBox(_T("The attempt to connect was forcefully rejected.试图联系的尝试被强烈拒绝了\n")); break; case WSAEDESTADDRREQ: AfxMessageBox(_T("A destination address is required.需要一个目标地址\n")); break; case WSAEFAULT: AfxMessageBox(_T("The lpSockAddrLen argument is incorrect.地址长度不对\n")); break; case WSAEINVAL: AfxMessageBox(_T("The socket is already bound to an address.套接字已经绑定到一个地址。\n")); break; case WSAEISCONN: AfxMessageBox(_T("The socket is already connected.套接字已经连接了。\n")); break; case WSAEMFILE: AfxMessageBox(_T("No more file descriptors are available.没有更多的文件描述符可用\n")); break; case WSAENETUNREACH: AfxMessageBox(_T("The network cannot be reached from this host ") _T("at this time.\n")); break; case WSAENOBUFS: AfxMessageBox(_T("No buffer space is available. The socket ") _T("cannot be connected.没有缓冲空间可用。套接字无法连接\n")); break; case WSAENOTCONN: AfxMessageBox(_T("The socket is not connected.套接字没有连接。\n")); break; case WSAENOTSOCK: AfxMessageBox(_T("The descriptor is a file, not a socket.描述符是一个文件,而不是一个套接字\n")); break; case WSAETIMEDOUT: AfxMessageBox(_T("The attempt to connect timed out without ") _T("establishing a connection. \n")); break; default: TCHAR szError[256]; _stprintf_s(szError, _T("OnConnect error: %d"), nErrorCode); AfxMessageBox(szError); break; } AfxMessageBox(_T("Please close the application")); }
//连接成功后,此处可以添加自己定义的处理程序! CAsyncSocket::OnConnect(nErrorCode); }