我正在尝试编写一些代码,这些代码将生成两个独立的代码块来监听连接。
int runsocket()
{
int socket_desc , client_sock , c;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
pthread_t thread_id;
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
puts("Connection accepted");
if( pthread_create( &thread_id , NULL , connection_handler , (void*) &client_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
//pthread_join( thread_id , NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
/*
* This will handle connection for each client
* */
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char *message , client_message[2000];
//Send some messages to the client
message = "Greetings! I am your connection handler\n";
write(sock , message , strlen(message));
message = "Now type something and i shall repeat what you type \n";
write(sock , message , strlen(message));
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
//end of string marker
client_message[read_size] = '\0';
//Send the message back to client
write(sock , client_message , strlen(client_message));
//clear the message buffer
memset(client_message, 0, 2000);
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
return 0;
}
现在,理论上说,我有一个runsocket2(),它还使用单独的connection_handler函数在单独的端口上打开一个套接字。在我的主要部分,我调用了runsocket();和runsocket2()。只运行socket();通过runsocket2(),它被执行并从那一点冻结永远不会被打电话我怎样才能解决这个问题并有效地执行它们?
我遇到的真正问题是使用一个websocket库,它有一个调用:libwebsock_wait(ctx);
一旦调用它,就是这样 - 它下面的所有代码都不再被执行,因为它实际上创建了一个循环。我希望能够强制一个单独的套接字监听一个单独的端口,并通过websocket外部处理数据。如果我调用runsocket();在libwebsock_wait(ctx)之前;然后程序成功开始侦听套接字8888,但不会启动websocket。关于如何抵消这种行为的任何想法?
答案 0 :(得分:0)
accept
调用的要点是阻止并等待传入连接。因此永远不会调用runsocket2()
,runsocket()
&#34;冻结&#34;正如它应该。您可以使用socket(AF_INET|SOCK_NONBLOCK, SOCK_STREAM, 0)
将套接字设置为非阻止,但您仍然需要不断检查传入连接。您可以创建套接字并使用select
语句。 (参见手册页)。或者最好的方法是线程runsocket()