恩。应该能实现你的要求
首先socket不是一个阻塞方法,它不会自动去连serverSocket,而是你connect一次它就去连一次,socket本身不存在什么连接server端超时,所以客户端的连接超时是由你的程序去控制的,比如用线程。
其次,恶意连接这个问题,其实我已经给你解决了,在server端拿到socket后,不就能用socket.setSoTimeout()来设置连接时间了么?
bool CRemoteLink::Connect(){
OnDisconnected() // 如果已经连接,则断开
if(!m_bUseProxy)
{
m_iConnStatus = SS_CONNECTING // 正在连接状态
GNTRACE ("开始连接到远程服务器[%s][%ld]...\n", m_strip.c_str(), m_port)
// 建立套接字, 准备连接到服务器
m_socket = ::socket(AF_INET, SOCK_STREAM, 0)
if (socket <0) {
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_CREATE, MSG_SE_CREATE)
return false
}
// 设为异步 *** 作方式
unsigned long on = 1
if (::ioctlsocket(m_socket, FIONBIO, &on) <0) {
::closesocket(m_socket)
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_CREATE, MSG_SE_CREATE)
return false
}
sockaddr_in addr
memset(&addr, 0, sizeof(addr))
addr.sin_family = AF_INET
addr.sin_addr.s_addr = inet_addr(m_strip.c_str())
addr.sin_port = htons(m_port)
int rt
rt = ::connect(m_socket, (sockaddr *) &addr, sizeof(addr))
if (rt == 0) {
OnConnected()
return true
}
// ==================================================================
timeval to
// 首先建立连接
fd_set wfds
fd_set efds
FD_ZERO(&wfds)
FD_ZERO(&efds)
// test shutdown event each 100ms.
to.tv_sec = 0
// CONNECT_TIMEOUT
to.tv_usec = 100000
int it = 0
while(!m_meShutdown.Wait(0) &&!m_meConnStop.Wait(0))
{
FD_SET(m_socket, &wfds)
FD_SET(m_socket, &efds)
int n = select(m_socket + 1, NULL, &wfds, &efds, &to)
if (n >0) {
if(FD_ISSET(m_socket, &wfds))
{
OnConnected()
return true
}
else
{
//int err = ::WSAGetLastError()
//const char* msg = GetLastErrorMessage(err)
GNTRACE ("CRemoteLink::Connect : connection attempt failed!\n")
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_CONN, MSG_SE_CONN)
break
}
} else if (n <0) { // Select Error
int err = ::WSAGetLastError()
const char* msg = GetLastErrorMessage(err)
GNTRACE ("CRemoteLink::Connect : Select Error.[%d] - %s\n", err, msg)
if(m_pCallBack)
m_pCallBack->OnSocketError(err, msg)
break
}
else
{
it += 100
if(it >30000) // 连接超时 -- (30S)
{
GNTRACE ("CRemoteLink::Connect : Time out.\n")
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_TIMEOUT, MSG_SE_TIMEOUT)
break
}
}
}
if(m_meConnStop.Wait(0))
{
GNTRACE("连接过程进行时被取消。\n")
}
}
else
{
// 通过代理服务器连接
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)