源码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void start() {
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(8080);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
struct sockaddr_in client_addr;
char client_ip[INET_ADDRSTRLEN] = "";
int clientfd = 0;
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
bind(listenfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
listen(listenfd, 128);
printf("listen client @port=%d...\n", 8080);
int lastfd = listenfd;
int i;
fd_set read_set, total_set;
FD_ZERO(&read_set);
FD_SET(listenfd, &total_set);
while(1) {
read_set = total_set;
int z = select(lastfd + 1, &read_set, NULL, NULL, NULL);
if (z > 0) {
if (FD_ISSET(listenfd, &read_set)) {
socklen_t client_len = sizeof(client_addr);
clientfd = accept(listenfd, (struct sockaddr*)&client_addr, &client_len);
inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
printf("----------------------------------\n");
printf("client ip=%s, port=%d\n", client_ip, ntohs(client_addr.sin_port));
FD_SET(clientfd, &total_set);
lastfd = clientfd;
if (0 == --z) {
continue;
}
}
for (i = listenfd + 1; i <= lastfd; i++) {
if (FD_ISSET(i, &read_set)) {
char recv_buf[1024] = "";
int rs = read(i, recv_buf, sizeof(recv_buf));
if (rs == 0) {
close(i);
FD_CLR(i, &total_set);
} else {
printf("%s\n", recv_buf);
// write(0, recv_buf, rs);
}
}
}
}
}
}
int main() {
start();
return 0;
}
编译
gcc -o select select.c
测试
eric@LEGION:~/study_java$ ./select
listen client @port=8080...
----------------------------------
client ip=127.0.0.1, port=10966
----------------------------------
client ip=127.0.0.1, port=10975
111
222