以下是代码:
int main(int argc, char **argv)
{
int listener_socket, new_socket;
struct sockaddr_in server_address;
pthread_t player_queue_processing;
pthread_attr_t attr;
Network_Code wait_message = WAIT;
Network_Code incoming_message;
if(pthread_attr_init(&attr) != 0){
perror("Error initializing thread attributes");
return 1;
}
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(pthread_create(&player_queue_processing, &attr, run, NULL) != 0){
perror("Error creating thread");
return 1;
}
if((listener_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("Error creating socket");
return 1;
}
if((player_queue = qu_allocate()) == NULL){
perror("Error creating player queue");
return 1;
}
memset(&server_address, 0, sizeof server_address);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(449);
printf("Listening on port: %d\n", ntohs(server_address.sin_port));
bind(listener_socket, (struct sockaddr*)&server_address, sizeof server_address);
if(listen(listener_socket, BACKLOG) == -1){
perror("Listen");
return 1;
}
while(1){
new_socket = accept(listener_socket, (struct sockaddr*)NULL, NULL);
read(new_socket, &incoming_message, sizeof incoming_message);
if(incoming_message != I_WANT_TO_PLAY){
close(new_socket);
continue;
}
write(new_socket, &wait_message, sizeof wait_message);
if(qu_enqueue(player_queue, (void *)(size_t)new_socket) == QU_ERROR)
perror("Error enqueuing player");
}
}
netstat -tulpn
tcp 0 0 0.0.0.0:48577 0.0.0.0:* LISTEN
当客户端使用端口48577时,它可以工作。问题是服务器绑定在错误的端口上,即使我正在调用htons()
。为什么会这样?
每次端口更改时,我都会重启多次。我正在运行Debian GNU / Linux jessie / sid 64位