tcp_server.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
// socket
int listenFd = socket(AF_INET, SOCK_STREAM, 0);
if (listenFd < 0) {
perror("socket");
exit(1);
}
struct sockaddr_in serverAddr;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
// bind
if (bind(listenFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
perror("bind");
exit(2);
}
// listen
if (listen(listenFd, 30) < 0) {
perror("listen");
exit(3);
}
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
while (1) {
int connFd = accept(listenFd, (struct sockaddr*)&clientAddr, &clientAddrLen);
if (connFd < 0) {
perror("accept");
close(listenFd);
exit(4);
}
// use select.
char buf[1024] = {0};
fd_set readFds;
fd_set exceptionFds;
FD_ZERO(&readFds);
FD_ZERO(&exceptionFds);
while (1) {
// bind the connFd and fd_set.
FD_SET(connFd, &readFds);
FD_SET(connFd, &exceptionFds);
int ret = select(connFd + 1, &readFds, NULL, &exceptionFds, NULL);
if (ret < 0) {
perror("select");
return -1;
}
if (FD_ISSET(connFd, &readFds)) { //read event.
read(connFd, buf, 1024);
printf("recv:%s\n", buf);
}
if (FD_ISSET(connFd, &exceptionFds)) { //exception event.
}
}
close(connFd);
}
close(listenFd);
return 0;
}