gpt4 book ai didi

C - 使用 select() 创建 UTP 服务器/客户端聊天室

转载 作者:太空宇宙 更新时间:2023-11-04 04:19:57 24 4
gpt4 key购买 nike

我应该让服务器广播它从客户端获得的消息到所有其他连接的客户端。

实际的广播有效,但我不知道如何阻止客户端在我 CTRL+C 服务器时无限打印“[client]Received from friends:”,

当我 CTRL+C 任何连接的客户端时,如何阻止服务器无限打印“[server]Message received...”。或者如何在某处添加验证,以便客户端在尝试发送字符串“quit”时断开连接

也许我要求太多了,但是有人可以向我解释一下 select(..) 到底做了什么吗?我知道它正在监视 FD,但我无法完全理解 1 秒后发生了什么(逐步)。它是否通过所有 FD,每个 FD 1 秒然后重复?我有点明白了,但不完全是。无论如何谢谢你

服务器

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>


#define PORT 3050 //The port used by Clients

extern int errno;

char * conv_addr (struct sockaddr_in address)
{
static char str[25];
char port[7];


strcpy (str, inet_ntoa (address.sin_addr)); /* client IP */

bzero (port, 7); /* PORT */
sprintf (port, ":%d", ntohs (address.sin_port));
strcat (str, port);
return (str);
}

void Msgs(int fd,int sd,fd_set fds,int nr);

int main ()
{
struct sockaddr_in server_addr; /* struct for Server */
struct sockaddr_in client_addr; /* struct for Clients */
fd_set readfds; /* ready-to-read File Descriptors */
fd_set actfds; /* active/existant File Descriptors */
struct timeval tv; /* time thing, for select() */
int ServerSocketFD, ClientSocketFD; /* Socket descriptors */
int optval=1; /* ????*/
int fd; /* FD used to pass through all FDs */
int nfds; /* max number of FDs */


(ServerSocketFD = socket (AF_INET, SOCK_STREAM, 0));


setsockopt(ServerSocketFD, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval) );


bzero (&server_addr, sizeof (server_addr));

server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl (INADDR_ANY);
server_addr.sin_port = htons (PORT);


bind (ServerSocketFD, (struct sockaddr *) &server_addr, sizeof(struct sockaddr) );


listen (ServerSocketFD, 5); //listen to maximum 5 clients,no more

FD_ZERO (&actfds);
FD_SET (ServerSocketFD, &actfds); /* Add the only existant one for now */

tv.tv_sec = 1; /* wait 1s */
tv.tv_usec = 0;

nfds = ServerSocketFD; /* max value of currently used FDs */

printf ("[server] Waiting at port :%d...\n", PORT);
fflush (stdout);


while (1) /* serve clients CONCURRENTLY */
{
bcopy ((char *) &actfds, (char *) &readfds, sizeof (readfds)); /* copy all existing FDs in actfds vector to the read-to-read-FDs vector */

select(nfds+1, &readfds, NULL, NULL, &tv);

if (FD_ISSET (ServerSocketFD, &readfds)) /* if ServerSocket is ready to read stuff */
{
bzero (&client_addr, sizeof (client_addr));

int len = sizeof (client_addr);
ClientSocketFD = accept (ServerSocketFD, (struct sockaddr *) &client_addr, &len);

if (nfds < ClientSocketFD) /* adjust max FD, for select */
nfds = ClientSocketFD;

/* Add this accepted sockets' FD to the existing FDs */
FD_SET (ClientSocketFD, &actfds);

printf("[server] Client connected, with FD %d, from this address %s.\n",ClientSocketFD, conv_addr (client_addr));
fflush (stdout);
}

for (fd = 0; fd <= nfds; fd++) /* all FDs*/
{
if (fd != ServerSocketFD && FD_ISSET (fd, &readfds)) /* is a client ready to send/get messages? */
{
Msgs(fd,ServerSocketFD,actfds,nfds);
}
}
}
}

void Msgs(int fd,int ServerSocketFD,fd_set fds,int nrFD)
{
char buffer[100];
int bytes;
char msg[100];

bytes = read (fd, msg, sizeof (buffer));

/*
if(strstr(msg,"quit")!=0)
{
FD_CLR(fd, &fds);
close(fd);
exit(1);
}
*/
printf ("[server]Message received...%s\n", msg);

for(int i=0;i<=nrFD;i++)
{
if(i!=fd && i!=ServerSocketFD)
{
write (i, msg, bytes);
}
}

}

客户

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>


extern int errno;

int port;

int main (int argc, char *argv[])
{

int ClientSocketFD;
struct sockaddr_in server_addr;
char msg[100];
char reply[100];


if (argc != 3)
{
printf ("[client] Sintax: %s <server_address> <port>\n", argv[0]);
return -1;
}


port = atoi (argv[2]);
ClientSocketFD = socket (AF_INET, SOCK_STREAM, 0);


server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons (port);


connect(ClientSocketFD, (struct sockaddr *) &server_addr,sizeof (struct sockaddr));



int pid;
if((pid=fork())==-1)
{
perror("Error fork()");
exit(10);
}
if(pid==0) //CHILD
{
while(1)
{
bzero(msg,100);
printf ("[client]Send something to other clients: ");
fflush (stdout);

read (0, msg, 100);
if(strstr(msg,"quit")!=0)
{
break;
}

write (ClientSocketFD, msg, 100);
}

exit(7);
}
else if(pid > 0) //PARENT
{
while(1)
{
bzero(reply,100);
read (ClientSocketFD, reply, 100);

printf ("[client]Received from friends: %s\n", reply);
}
}

close (ClientSocketFD);

}

最佳答案

I have no idea how to stop the clients from infinitely printing "[client]Received from friends:" when I CTRL+C the server

read()如果服务器终止,则返回 0,因此替换 while(1)通过

在客户端 PARENT 中循环
        while (bzero(reply, 100), read(ClientSocketFD, reply, 100) > 0)
printf("[client]Received from friends: %.100s\n", reply);
kill(pid, SIGTERM); // terminate also the child

(和 #include <signal.h> )。

how to stop the Server from infinitely printing "[server]Message received..." when I CTRL+C any of the connected Clients

read()如果客户端终止,则返回 0,因此调用

                Msgs(fd, ServerSocketFD, &actfds, nfds);

更改Msgs()输入

void Msgs(int fd, int ServerSocketFD, fd_set *fds, int nrFD)

并在Msgs()bytes = read (fd, msg, sizeof (buffer)); 之后添加

  if (bytes <= 0) { FD_CLR(fd, fds); close(fd); return; }

could someone please explain to me what exactly does select(..) do? I understand that it's monitoring the FDs, but I can't fully understand what's going on(step-by-step) after 1 second. Does it go through all FDs ,1 second for each then repeat?

正如 wildplasser 在他的评论中指出的那样,select()可能会更改超时参数以指示剩余时间,因此在没有 FD 事件的 1 秒后,我们很可能会以零超时和无用的繁忙循环结束。我们需要一个 select()仅当我们想在特定时间内没有任何受监视的 FD 准备就绪时执行某些操作时才超时,因此在您的情况下最好完全不指定超时:

        select(nfds+1, &readfds, NULL, NULL, NULL);

关于C - 使用 select() 创建 UTP 服务器/客户端聊天室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739576/

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