我正在尝试编写一些代码,这些代码将生成两个独立的代码块来侦听连接。
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 handlern";
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] = ' ';
//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函数在一个单独端口上打开一个套接字。在我的main中,我调用runsocket();和runsocket2()。仅运行socket();被执行,并从那时起冻结,使用runsocket2();从未被召唤。我如何绕过这一点,并有效地执行这两项任务?
我遇到的真正问题是使用一个websocket库,它有一个调用:libwebsocket_wait(ctx);
一旦调用了它,就这样了——它下面的所有代码都不再执行,因为它本质上创建了一个循环。我希望能够强制一个独立的套接字在一个独立端口上侦听,并在websocket之外通过它处理数据。如果我调用runsocket();在libwebstock_wait(ctx)之前;则程序成功地开始侦听套接字8888,但不启动websocket。关于我如何应对这种行为,有什么想法吗?
accept
调用的目的是阻止并等待传入连接。因此runsocket2()
永远不会被调用,runsocket()
也会"冻结"。您可以使用socket(AF_INET|SOCK_NONBLOCK, SOCK_STREAM, 0)
将套接字设置为非阻塞,但仍需要不断检查传入连接。您可以创建套接字并使用select
语句。(请参阅手册页)。或者最好的方法是线程runsocket()