判断socket是否有效 libevent
1个回答
展开全部
1)创建nonblock的socket,
2)调用connect连接服务器,检查返回值,判断是否是阻塞了,如果是,就设置等待 EV_WRITE事件:
event_set(&m_evSocket, m_iSockFd, EV_WRITE, onConnect, this);
3)EV_WRITE返回后,判断event是否为EV_WRITE,
关键一点:如果EV_WRITE,还要进一步判断sockopt是否正确。
代码片段如下:
[cpp] view plain copy
bool CClientSocket::connectSocket(string szHostAddr, int nHostPort){
if (m_iSockFd == -1){
createSocket();
}
struct sockaddr_in Ser_addr;
memset(&Ser_addr, 0, sizeof(struct sockaddr_in));
Ser_addr.sin_family = AF_INET;
Ser_addr.sin_addr.s_addr = inet_addr(szHostAddr.c_str());
Ser_addr.sin_port = htons(nHostPort);
2)调用connect连接服务器,检查返回值,判断是否是阻塞了,如果是,就设置等待 EV_WRITE事件:
event_set(&m_evSocket, m_iSockFd, EV_WRITE, onConnect, this);
3)EV_WRITE返回后,判断event是否为EV_WRITE,
关键一点:如果EV_WRITE,还要进一步判断sockopt是否正确。
代码片段如下:
[cpp] view plain copy
bool CClientSocket::connectSocket(string szHostAddr, int nHostPort){
if (m_iSockFd == -1){
createSocket();
}
struct sockaddr_in Ser_addr;
memset(&Ser_addr, 0, sizeof(struct sockaddr_in));
Ser_addr.sin_family = AF_INET;
Ser_addr.sin_addr.s_addr = inet_addr(szHostAddr.c_str());
Ser_addr.sin_port = htons(nHostPort);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询