2、在默认sysctl.conf文件中添加net.ipv4.tcp_timestamps=0值。
如果你确定,真的不需要等这么久,或者用户希望可以随时中上连接过程,那么一般是用 非阻塞模式来做的. 看看我的这段连接代码(节选),可以作为TCP连接的典范: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条)