这是我的代码:
void error(const char *msg)
{
perror(msg);
exit(1);
}
void sServer::acceptClientConnections(int listenerSocket)
{
struct sockaddr clientAddress;
socklen_t sizeOfClientAddress = sizeof(clientAddress);
while (true)
{
int newConnection = accept(listenerSocket, &clientAddress, &sizeOfClientAddress);
std::cout << "Someone connected ... " <<std::endl;
liveConnections.push_back(newConnection);
}
}
int sServer::getServerListenerSocket()
{
return serverListenerSocket;
}
sServer::sServer(int port)
{
int serverListenerSocket;
struct sockaddr_in serv_addr;
serverListenerSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverListenerSocket < 0)
error("ERROR opening a socket. Cannot start sever. Exiting ...");
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
std::cout << "Host ip: " << serv_addr.sin_addr.s_addr << "\n";
if ( bind(serverListenerSocket, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0 )
error("ERROR on binding server socket. Are you running another instance of this server ?");
listen(serverListenerSocket, 45);
}
这样称呼:
int main()
{
sServer superServer(9889);
std::thread handleConnections( &sServer::acceptClientConnections, superServer, superServer.getServerListenerSocket() );
}
我期待接受等待传入连接,并且当连接进入时,变为活动状态。
但是,当我运行程序时,它会不断打印“有人连接......”,即使没有连接。
具有讽刺意味的是,如果我在构造函数的末尾启动线程,它运行良好。
您能解释为什么会发生这种情况以及接受连接的正确方法是什么?
答案 0 :(得分:1)
现在我们确定了错误,问题是构造函数中的局部变量:
sServer::sServer(int port)
{
int serverListenerSocket;
删除它。它隐藏了同名的类成员,因此后者永远不会被设置,因此accept()
正在使EBADF,
返回-1,从不显示已接受的连接,吸烟等等。
在构造函数中启动线程时它起作用的原因是局部变量仍在范围内。