现在,我的代码允许多个客户端连接到服务器并向服务器发送消息,然后将消息发送回发送它的客户端。我试图弄清楚如何让服务器将收到的消息发送给所有客户端。
我考虑将sd存储在一个数组中,然后写入每个sd,但我先打印了sd,它总是相同的数字(4),所以我不确定我是什么应该做
我目前的代码:
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "networking.h"
void process( char * s );
void sub_server( int sd );
int main() {
int sd, connection;
sd = server_setup();
while (1) {
connection = server_connect( sd );
int f = fork();
if ( f == 0 ) {
close(sd);
sub_server( connection );
exit(0);
}
else {
close( connection );
}
}
return 0;
}
void sub_server( int sd ) {
char buffer[MESSAGE_BUFFER_SIZE];
while (read( sd, buffer, sizeof(buffer) )) {
printf("[SERVER %d] received: %s\n", getpid(), buffer );
process( buffer );
write( sd, buffer, sizeof(buffer));
}
}
void process( char * s ) {
while ( *s ) {
*s = (*s - 'a' + 13) % 26 + 'a';
s++;
}
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "networking.h"
int main( int argc, char *argv[] ) {
char *host;
if (argc != 2 ) {
printf("host not specified, conneting to 127.0.0.1\n");
host = "127.0.0.1";
}
else
host = argv[1];
int sd;
sd = client_connect( host );
char buffer[MESSAGE_BUFFER_SIZE];
while (1) {
printf("enter message: ");
fgets( buffer, sizeof(buffer), stdin );
char *p = strchr(buffer, '\n');
*p = 0;
write( sd, buffer, sizeof(buffer) );
read( sd, buffer, sizeof(buffer) );
printf( "received: %s\n", buffer );
}
return 0;
}
networking.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
void error_check( int i, char *s ) {
if ( i < 0 ) {
printf("%d\n", i);
printf("[%s] error %d: %s\n", s, errno, strerror(errno) );
exit(1);
}
}
int server_setup() {
int sd;
int i;
sd = socket( AF_INET, SOCK_STREAM, 0 );
error_check( sd, "server socket" );
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = INADDR_ANY;
sock.sin_port = htons(9001);
i = bind( sd, (struct sockaddr *)&sock, sizeof(sock) );
error_check( i, "server bind" );
return sd;
}
int server_connect(int sd) {
int connection, i;
i = listen(sd, 1);
error_check( i, "server listen" );
struct sockaddr_in sock1;
unsigned int sock1_len = sizeof(sock1);
connection = accept( sd, (struct sockaddr *)&sock1, &sock1_len );
error_check( connection, "server accept" );
printf("[server] connected to %s\n", inet_ntoa( sock1.sin_addr ) );
return connection;
}
int client_connect( char *host ) {
int sd, i;
sd = socket( AF_INET, SOCK_STREAM, 0 );
error_check( sd, "client socket" );
struct sockaddr_in sock;
sock.sin_family = AF_INET;
inet_aton( host, &(sock.sin_addr));
sock.sin_port = htons(9001);
printf("[client] connecting to: %s\n", host );
i = connect( sd, (struct sockaddr *)&sock, sizeof(sock) );
error_check( i, "client connect");
return sd;
}
非常感谢帮助和解释(我也是C的新手,所以请尝试解释)