i trying implement small c++ server. want receive connections clients, , handle of these connections in own threads. far good. long introduce no threads, works fine, try create thread client, accept returns -1/error.
here code:
void server::run() { cout << "starting server on port " << this->port << "..." << endl; this->socket_fd = socket(af_inet, sock_stream, 0); if (this->socket_fd < 0) { perror("creating socket"); exit(1); } struct sockaddr_in myaddr; myaddr.sin_family = af_inet; myaddr.sin_port = htons(this->port); inet_aton("192.168.201.58", &myaddr.sin_addr); if ( bind(this->socket_fd, (struct sockaddr*)&myaddr, sizeof(myaddr))) { perror("bind"); exit(1); } if (listen(this->socket_fd, 5)) { perror("listen"); exit(1); } /* waiting clients */ cout << "waiting connection..." << endl; int client_fd; struct sockaddr_in remote_addr; socklen_t remote_addr_len; while (this->running) { client_fd = accept(this->socket_fd, (struct sockaddr*)&remote_addr, &remote_addr_len); if (client_fd <= 0) { perror("accept"); this->running = false; continue; } cout << "got new client address " << inet_ntoa(remote_addr.sin_addr) << endl; client new_client(client_fd, remote_addr.sin_addr); //new_client.run(); std::thread t ( &client::run, &new_client ); //t.detach(); } }
when trying connect via telnet, "accept: invalid argument". comment out line create thread
std::thread t ( &client::run, &new_client );
everything works fine.
i appreciate hints.
try:
std::thread t ( &client::run, std::move(new_client) );
according the documentation, that's how should call it.
Comments
Post a Comment