diff --git a/README.txt b/README.txt index bfe8f5a..4e26aba 100644 --- a/README.txt +++ b/README.txt @@ -1,4 +1,4 @@ -#Multiuser udp server for broadcasting music +#Multiuser tcp server for broadcasting music #Record audio in sterio @@ -6,4 +6,4 @@ arecord -D loopout --buffer-size=20000 -f S16_LE -t raw -r 48000 -c 2 | ./server #Geting raw pcm data and send to speaker -echo "JOIN" | nc -u server_ip server_port | aplay -r 48000 -f S16_LE -c 2 +nc server_ip server_port | aplay -r 48000 -f S16_LE -c 2 diff --git a/server.c b/server.c index 0389814..55d42a4 100644 --- a/server.c +++ b/server.c @@ -9,13 +9,14 @@ #include #include -#define PORT 8889 +#define PORT 8888 #define BUFF_SIZE 8192 #define MAX_CLIENTS 125 typedef struct { int fd; struct sockaddr_in clients[MAX_CLIENTS + 1]; + int client_fds[MAX_CLIENTS + 1]; } DATA; void *process_clients(void *p) { @@ -29,21 +30,20 @@ void *process_clients(void *p) { socklen_t len = sizeof(struct sockaddr_in); for (size_t i = 0; i < MAX_CLIENTS; i++) - sendto(data->fd, buf, ret, 0, (struct sockaddr *)&data->clients[i], len); + if (data->client_fds[i] != -1) + if (sendto(data->client_fds[i], buf, ret, 0, (struct sockaddr *)&data->clients[i], len) != ret) + data->client_fds[i] = -1; } } int main(void) { signal(SIGPIPE, SIG_IGN); - int fd = socket(AF_INET, SOCK_DGRAM, 0); + int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) goto ERROR_WITHOUTCLOSE; - struct timeval tv = {.tv_sec = 0, .tv_usec = 50}; - if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) - goto ERROR; - + struct timeval tv = {.tv_sec = 0, .tv_usec = 0}; if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) goto ERROR; @@ -58,24 +58,31 @@ int main(void) { if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) goto ERROR; + if (listen(fd, -1) < 0) + goto ERROR; + + /* Thread of common buffer */ static DATA data; + memset(data.client_fds, -1, sizeof(data.client_fds)); data.fd = fd; pthread_t td; pthread_create(&td, NULL, process_clients, (void *)&data); - int last = 0; - char buf[1]; - - socklen_t len = sizeof(struct sockaddr_in); + /* Get clients */ + socklen_t len = sizeof(addr); while (1) { - if (last <= MAX_CLIENTS) { - if (recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&data.clients[last], &len) > 0) - last++; - } + int client_fd = accept(fd, (struct sockaddr *)&addr, &len); + if (client_fd < 0) + continue; - else - last = 0; + for (size_t i = 0; i < MAX_CLIENTS; i++) { + if (data.client_fds[i] == -1) { + data.clients[i] = addr; + data.client_fds[i] = client_fd; + break; + } + } } ERROR: