gpt4 book ai didi

调用 recv() block 输入

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:12 26 4
gpt4 key购买 nike

我的套接字有问题。我有一个服务器和一个客户端。

程序的目的:

客户端/服务器连接(都互相发送消息)客户端发送消息;服务器读取消息;服务器将消息返回给客户端。

但是我遇到了死锁,因为客户端和服务器都在等待接收消息。代码:

Server.c

message = "Client connection handler ok\n";
write(sock , message , strlen(message));

message = "type something and i'll 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 )
{
puts(client_message);

//Send the message back to client
write(sock , client_message , strlen(client_message));

bzero(client_message,2000);
}

客户端.c

//Here I print the two messages You can see server side code:
//- Client connection handler ok
//- type something and i'll repeat what you type
while( (read_size = recv(sockfd , client_message , 2000 , 0)) > 0 )
{
printf("%s\n",client_message);
bzero(client_message,2000);
}

在执行代码的过程中,我同时在客户端和服务器端保持阻塞状态。

我该如何解决这个问题?

最佳答案

您正在寻找 select功能。你告诉 select 等待标准输入和您的套接字。

您的客户端将如下所示(未经测试的代码):

/* This is a bit mask where each bit corresponds to a file descriptor.
It is an in/out parameter, so you set some bits to tell select what
to wait on, and then select sets bits in it to tell you what fd has
data waiting for you to read. */
fd_set read_fds;

while(1){
int fd_max = STDIN_FILENO;

/* Set the bits for the file descriptors you want to wait on. */
FD_ZERO(&read_fds);
FD_SET(STDIN_FILENO, &read_fds);
FD_SET(sockfd, &read_fds);

/* The select call needs to know the highest bit you set. */
if( sockfd > fd_max ) { fd_max = sockfd; }

/* Wait for any of the file descriptors to have data. */
if (select(fd_max + 1, &read_fds, NULL, NULL, NULL) == -1)
{
perror("select:");
exit(1);
}

/* After select, if an fd's bit is set, then there is data to read. */
if( FD_ISSET(sockfd, &read_fds) )
{
/* There is data waiting on your socket. Read it with recv(). */
}

if( FD_ISSET(STDIN_FILENO, &read_fds )
{
/* The user typed something. Read it fgets or something.
Then send the data to the server. */
}
}

不要忘记在从标准输入读取后将数据发送到您的服务器。在您发布的代码中,您实际上并未向服务器发送任何数据,因此服务器不会唤醒。

关于调用 recv() block 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com