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
{
// 通过代理服务器连接
1. 建议lz使用socket套接字。这个方式可以很好的实现client/server模式,tcp和udp协议都可以选择。使用socket来实现两台电脑的进程间通信,要先理解一些函数,如socket,binder,listen,connect,recv,send等等。。。2. lz可以上网搜索关键字“linux socket编程”,或追问我。
你的client有问题,连接之前没有指定server的ip。你只指定了端口。
struct sockaddr_in servaddr
bzero(&servaddr,sizeof(servaddr))
servaddr.sin_family=AF_INET
servaddr.sin_port=htons(HELLO_WORLD_SERVER_PORT)
servaddr.sin_addr.s_addr=inet_addr(serverip)//加上server的ip即可
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)