wip similar eric
This commit is contained in:
26
mini_serv.c
26
mini_serv.c
@@ -33,6 +33,11 @@
|
||||
|
||||
#define BUFSIZE 42000
|
||||
|
||||
typedef struct s_clients {
|
||||
int id;
|
||||
char msg[BUFSIZE - 20];
|
||||
} t_clients;
|
||||
|
||||
void error(char *str) {
|
||||
write(2, str, strlen(str));
|
||||
exit(1);
|
||||
@@ -75,10 +80,10 @@ int main(int ac, char **av) {
|
||||
int port;
|
||||
int max_fd;
|
||||
int ret;
|
||||
int clients[FD_SETSIZE];
|
||||
t_clients clients[FD_SETSIZE];
|
||||
t_clients client;
|
||||
|
||||
char buf[BUFSIZE];
|
||||
char tmpbuf[BUFSIZE];
|
||||
char msg[BUFSIZE];
|
||||
|
||||
struct sockaddr_in addr;
|
||||
@@ -99,8 +104,6 @@ int main(int ac, char **av) {
|
||||
max_fd = server_fd;
|
||||
client_id = 0;
|
||||
|
||||
/*
|
||||
*/
|
||||
while (1) {
|
||||
rdset = fdset;
|
||||
|
||||
@@ -110,7 +113,7 @@ int main(int ac, char **av) {
|
||||
if (FD_ISSET(server_fd, &rdset)) {
|
||||
client_fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
|
||||
FD_SET(client_fd, &fdset);
|
||||
clients[client_fd] = client_id;
|
||||
clients[client_fd].id = client_id;
|
||||
if (client_fd > max_fd)
|
||||
max_fd = client_fd;
|
||||
sprintf(msg, "server: client %d just arrived\n", client_id);
|
||||
@@ -126,19 +129,20 @@ int main(int ac, char **av) {
|
||||
bzero(buf, BUFSIZE);
|
||||
ret = recv(client_fd, buf, BUFSIZE, 0);
|
||||
if (ret == 0) {
|
||||
sprintf(msg, "server: client %d just left\n", clients[client_fd]);
|
||||
sprintf(msg, "server: client %d just left\n", clients[client_fd].id);
|
||||
broadcast(msg, &fdset, max_fd, server_fd, client_fd);
|
||||
FD_CLR(client_fd, &fdset);
|
||||
}
|
||||
else if (ret > 0) {
|
||||
|
||||
for(int i = 0, j = 0; buf[i] != '\n'; ++i, ++j) {
|
||||
tmpbuf[j] = buf[i];
|
||||
client = clients[client_fd];
|
||||
for(int i = 0, j = strlen(client.msg); i < ret; ++i, ++j) {
|
||||
client.msg[j] = buf[i];
|
||||
if (buf[i] == '\n') {
|
||||
tmpbuf[j] = '\0';
|
||||
sprintf(msg, "client %d: %s\n", clients[client_fd], tmpbuf);
|
||||
client.msg[j] = '\0';
|
||||
sprintf(msg, "client %d: %s\n", client.id, client.msg);
|
||||
broadcast(msg, &fdset, max_fd, server_fd, client_fd);
|
||||
bzero(tmpbuf, strlen(tmpbuf));
|
||||
bzero(client.msg, strlen(client.msg));
|
||||
j = -1;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user