Simple Socket Server based on C | |||
| |||
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <sys/uio.h> #include <unistd.h> #include <signal.h> /* the TCP port that is used for this example */ #define TCP_PORT 6500 #define SERV_HOST_ADDR "127.0.0.1" int main() { struct sockaddr_in server; struct sockaddr_in cliAddr; int sockFd; int sock; unsigned short cliLen; int i; signal(SIGCLD, SIG_IGN); sockFd = socket(AF_INET, SOCK_STREAM, 0); if(sockFd < 0) { perror("opening stream socket"); exit(1); } setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, 0, 0); memset((char *) &server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(TCP_PORT); if(bind(sockFd, (struct sockaddr *) &server, sizeof server) < 0) { fprintf(stdout, "bind error "); exit(0); } listen(sockFd, 5); cliLen = sizeof(cliAddr); for(i=0; ;i++) { int chpid; int cc=0; int rflag=0; int wflag=0; char buf[128]; sock = accept(sockFd, (struct sockaddr *)&cliAddr, (int *)&cliLen); if(sock < 0) { fprintf(stderr, "accept failed "); exit(0); }; chpid = fork(); switch(chpid) { case 0: signal(SIGPIPE, SIG_IGN); signal(SIGCLD, SIG_IGN); cc = recv(sock, buf, 128, rflag); if ( cc <= 0 ) { shutdown(sock, 0); } fprintf(stdout, "read "); cc = send(sock, buf, strlen(buf), wflag); if ( cc <= 0 ) { shutdown(sock, 1); } fprintf(stdout, "send ", cc); close(sock); break; case -1: perror("fork failed : "); close(sock); break; default: close(sock); break; } } close(sockFd); exit(0); } | |||
| |||
| |||
Login for comment |