Skip to content

Instantly share code, notes, and snippets.

@oxnz
Created May 3, 2014 13:59
Show Gist options
  • Save oxnz/0d3ac52d1f5c2166006a to your computer and use it in GitHub Desktop.
Save oxnz/0d3ac52d1f5c2166006a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
void errpro(int condition, const char *errmsg) {
if (condition) {
perror(errmsg);
exit(EXIT_FAILURE);
}
}
#define PORT 8888U
#define BACKLOG 16U
#define BUFLEN 64U
#define MAXCON 128U
int main() {
char buf[BUFLEN+1];
struct sockaddr_in server_addr, client_addr;
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
errpro(-1 == listen_fd, "socket");
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
errpro(-1 == bind(listen_fd, (struct sockaddr *)&server_addr,
sizeof(server_addr)), "bind");
errpro(-1 == listen(listen_fd, BACKLOG), "listen");
struct pollfd fds[MAXCON];
fds[0].fd = listen_fd;
fds[0].events = POLLIN;
int nfds = 1;
int i;
for (i = 1; i < MAXCON; ++i) {
fds[i].fd = -1;
}
int concnt = 0; // current connections count
static int loop = 0;
for (;;) {
printf("loop %d\n", ++loop);
int ret = poll(fds, nfds, 10000);
errpro(-1 == ret, "poll");
if (0 == ret) {
printf("timeout\n");
break;
}
if (fds[0].revents & POLLIN) {
int sockfd = accept(listen_fd, NULL, NULL);
errpro(-1 == sockfd, "accept");
++concnt;
for (i = 0; i < MAXCON; ++i) {
if (fds[i].fd < 0) {
fds[i].fd = sockfd;
fds[i].events = POLLIN;
printf("accept fds[%d] = %d\n", i, sockfd);
break;
}
}
errpro(MAXCON == i, "too many connections");
if (i+1 > nfds) {
nfds = i+1;
}
}
// read data
for (i = 1; i < nfds; ++i) {
if (fds[i].fd < 0) {
printf("skipped\n");
} else if (fds[i].revents & POLLIN) {
int ret = recv(fds[i].fd, buf, BUFLEN, 0);
errpro(-1 == ret, "recv");
if (0 == ret) {
printf("close fds[%d]\n", i);
close(fds[i].fd);
fds[i].fd = -1;
}
buf[ret] = '\0';
printf("message from %d:\n%s", i, buf);
while (BUFLEN == ret) {
ret = recv(fds[i].fd, buf, BUFLEN, 0);
errpro(-1 == ret, "recv");
}
} else if (fds[i].revents & POLLERR) {
printf("fds[%d] error\n", i);
errpro(EXIT_FAILURE, "POLLERR");
}
} // end of read data
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment