gpt4 book ai didi

c - 多客户端 C 服务器的异步 C 客户端

转载 作者:行者123 更新时间:2023-12-01 20:18:42 24 4
gpt4 key购买 nike

我有一个工作正常的客户端,但每当我运行一个新客户端时,有时我不会在已经运行的另一个客户端上收到发送的消息,而使用 telnet 时它工作完美,消息“广播”给所有连接的客户端,我希望每当收到一条消息给其中一个客户端时就显示出来,即使我还没有发送消息。我应该在客户端上使用 select 吗?应该改变什么?

客户端.c:

#include <stdio.h> //printf
#include <string.h> //strlen
#include <sys/socket.h> //socket
#include <arpa/inet.h> //inet_addr
#include <unistd.h>

int main(int argc , char *argv[]){
int sock;
struct sockaddr_in server;
char message[256] , server_reply[256];

//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");

server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 9034 );

//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0){
perror("connect failed. Error");
return 1;
}

puts("Connected\n");

//keep communicating with server
for(;;){

printf("Enter message: ");
memset(message, 0, 256);
fgets(message, 256,stdin);
// scanf("%s" , message);

//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}

//Receive a reply from the server
if( recv(sock , server_reply , 256 , 0) < 0)
{
puts("recv failed");
break;
}

printf("Server Reply: %s\n", server_reply);
server_reply[0]='\0';
}

close(sock);
return 0;
}

服务器.c:

/*
** selectserver.c -- a cheezy multiperson chat server
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define PORT "9034" // port we're listening on

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}

return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int main(void){
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select()
int fdmax; // maximum file descriptor number

int listener; // listening socket descriptor
int newfd; // newly accept()ed socket descriptor
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;

char buf[256]; // buffer for client data
int nbytes;

char remoteIP[INET6_ADDRSTRLEN];

int yes=1; // for setsockopt() SO_REUSEADDR, below
int i, j, rv;

struct addrinfo hints, *ai, *p;

FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);

// get us a socket and bind it
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) {
fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
exit(1);
}

for(p = ai; p != NULL; p = p->ai_next) {
listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (listener < 0) {
continue;
}

// lose the pesky "address already in use" error message
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) {
close(listener);
continue;
}

break;
}

// if we got here, it means we didn't get bound
if (p == NULL) {
fprintf(stderr, "selectserver: failed to bind\n");
exit(2);
}

freeaddrinfo(ai); // all done with this

// listen
if (listen(listener, 10) == -1) {
perror("listen");
exit(3);
}

// add the listener to the master set
FD_SET(listener, &master);

// keep track of the biggest file descriptor
fdmax = listener; // so far, it's this one

// main loop
for(;;) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);
}

// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == listener) {
// handle new connections
addrlen = sizeof remoteaddr;
newfd = accept(listener,
(struct sockaddr *)&remoteaddr,
&addrlen);

if (newfd == -1) {
perror("accept");
} else {
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax) { // keep track of the max
fdmax = newfd;
}
printf("selectserver: new connection from %s on "
"socket %d\n",
inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP, INET6_ADDRSTRLEN),
newfd);
}
} else {
// handle data from a client
memset(buf, 0, 256);
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
} else {
// we got some data from a client
for(j = 0; j <= fdmax; j++) {
// send to everyone!
if (FD_ISSET(j, &master)) {
// except the listener and ourselves
if (j != listener && j != i) {
if (send(j, buf, nbytes, 0) == -1) {
perror("send");
}
}
}
}
}
} // END handle data from client
} // END got new incoming connection
} // END looping through file descriptors
} // END for(;;)--and you thought it would never end!

return 0;
}

最佳答案

客户端在发送消息之前无法接收消息的原因是。

fgets(message, 256,stdin);

Will keep "reading" (and will therefore block) until an EOF or a newline character has been read from the input stream

另外,请注意

if( recv(sock , server_reply , 256 , 0) < 0)

blocks if there is nothing to read ,这将阻止该用户向服务器发送更多消息,直到从服务器读取新内容为止。假设你以前玩过网络游戏,我希望你能看到这样的设置是相当烦人的!

因此,我们必须找到某种方法来检查是否可以从 STDIN服务器套接字 读取数据而不会产生阻塞。使用select()将阻止我们阻塞服务器套接字,但在使用fgets()时对于STDIN不起作用 读取用户的输入。这是因为,如上所述,fgets() 会阻塞,直到检测到 EOF 或换行符为止。

我想到的主要解决方案是将fgets替换为buffer_message()方法,该方法仅在获胜时从STDIN读取读取时不会阻塞(我们将使用 select() 来实现这一点)。然后我们将读取的内容放入缓冲区。如果有完整消息,则该消息将被写入服务器。否则,我们将让控件继续执行程序,直到有东西要读或写为止。

这是我最近完成的大学作业中的代码,因此一小部分代码不是我的

声明:

//directives are above (e.g. #include ...)

//message buffer related delcartions/macros
int buffer_message(char * message);
int find_network_newline(char * message, int inbuf);
#define COMPLETE 0
#define BUF_SIZE 256

static int inbuf; // how many bytes are currently in the buffer?
static int room; // how much room left in buffer?
static char *after; // pointer to position after the received characters
//main starts below

主要:

//insert the code below into main, after you've connected to the server
puts("Connected\n");

//set up variables for select()
fd_set all_set, r_set;
int maxfd = sock + 1;
FD_ZERO(&all_set);
FD_SET(STDIN_FILENO, &all_set); FD_SET(sock, &all_set);
r_set = all_set;
struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0;

//set the initial position of after
after = message;

puts("Enter message: ");
//keep communicating with server
for(;;){

r_set = all_set;
//check to see if we can read from STDIN or sock
select(maxfd, &r_set, NULL, NULL, &tv);

if(FD_ISSET(STDIN_FILENO, &r_set)){

if(buffer_message(message) == COMPLETE){
//Send some data
if(send(sock, message, strlen(message) + 1, 0) < 0)//NOTE: we have to do strlen(message) + 1 because we MUST include '\0'
{
puts("Send failed");
return 1;
}

puts("Enter message:");
}
}

if(FD_ISSET(sock, &r_set)){
//Receive a reply from the server
if( recv(sock , server_reply , 256 , 0) < 0)
{
puts("recv failed");
break;
}

printf("\nServer Reply: %s\n", server_reply);
server_reply[0]='\0';

}
}

close(sock);
return 0;
//end of main

缓冲区功能:

int buffer_message(char * message){

int bytes_read = read(STDIN_FILENO, after, 256 - inbuf);
short flag = -1; // indicates if returned_data has been set
inbuf += bytes_read;
int where; // location of network newline

// Step 1: call findeol, store result in where
where = find_network_newline(message, inbuf);
if (where >= 0) { // OK. we have a full line

// Step 2: place a null terminator at the end of the string
char * null_c = {'\0'};
memcpy(message + where, &null_c, 1);

// Step 3: update inbuf and remove the full line from the clients's buffer
memmove(message, message + where + 1, inbuf - (where + 1));
inbuf -= (where+1);
flag = 0;
}

// Step 4: update room and after, in preparation for the next read
room = sizeof(message) - inbuf;
after = message + inbuf;

return flag;
}

int find_network_newline(char * message, int bytes_inbuf){
int i;
for(i = 0; i<inbuf; i++){
if( *(message + i) == '\n')
return i;
}
return -1;
}

附注

if( send(sock , message , strlen(message) , 0) < 0)

如果没有空间写入服务器,上面的代码也会阻塞,但这里不需要担心。另外,我想指出您应该为客户端和服务器实现的一些事情:

  1. Whenever you send data over a network, the standard newline is \r\n, or carriage return / newline, or simply the network newline.客户端和服务器之间发送的所有消息都应在末尾附加此内容。
  2. 您应该缓冲服务器和客户端之间发送的所有数据。为什么?因为您不能保证在一次读取套接字时收到消息中的所有数据包。我没有时间找到来源,但是使用 TCP/IP 时,消息/文件的数据包不必一起到达,这意味着如果您确实读取,您可能不会读取您想要读取的所有数据读书。 我对此不太熟悉,所以请进一步研究一下。愿意对此进行编辑/更正

关于c - 多客户端 C 服务器的异步 C 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29729561/

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