参照网上的代码,写了一个socket连接:
int Gameserver::connect(const char *ip, unsigned int port){
CCLOG("Client begin connect IP: %s:%d ",ip,port);
struct sockaddr_in sa;
struct hostent* hp;
hp = gethostbyname(ip);
if(!hp){
printf( "failed to create gethostbyname\n" );
return -1;
}
memset(&sa, 0, sizeof(sa));
memcpy((char*)&sa.sin_addr, hp->h_addr, hp->h_length);
sa.sin_family = hp->h_addrtype;
sa.sin_port = htons(port);
m_socketHandle = socket(sa.sin_family, SOCK_STREAM, 0);
if(m_socketHandle < 0){
printf( "failed to create socket\n" );
return -1;
}
if(::connect(m_socketHandle, (sockaddr*)&sa, sizeof(sa)) < 0){
printf( "failed to connect socket\n" );
printf("%s:%d,error:%d \n",ip,port,errno);
::close(m_socketHandle);
return -1;
}
CCLOG("Client connect OK ! IP: %s:%d ",ip,port);
CCNotificationCenter::sharedNotificationCenter()->postNotification("connectok", NULL);
return 0;
}
```
但是到 if(::connect(m_socketHandle, (sockaddr*)&sa, sizeof(sa)) < 0){
printf( "failed to connect socket\n" );
printf("%s:%d,error:%d\n",ip,port,errno);
::close(m_socketHandle);
return -1;
}
这里,总是返回-1,errno提示是ECONNREFUSED 61 /* Connection refused */
请问什么原因会导致这个问题呢?
另外我用java写了另外的socket方法,测试可以正常连接到服务器,说明服务器端应该是没有问题的。