Mercurial > hg > Members > nobuyasu > test
view cbcecho/#echoserver_cbc.cbc# @ 11:1e0cd7fade8b
add regen
author | nobuyasu <dimolto@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Sun, 19 Jun 2011 16:36:05 +0900 |
parents | |
children |
line wrap: on
line source
#include <stdio.h> #include <stdlib.h> /* exit() */ #include <string.h> /* bzero() */ #include <sys/types.h> #include <sys/socket.h> /* socket(), bind(), listen(), accept(), recv() */ #include <netinet/in.h> /* htons() */ #include <unistd.h> #include <pthread.h> #define PORT 8888 /* Listen’¤¹’¤ë’¥Ý’¡¼’¥È */ #define MAXDATA 1024 /* ’¼õ’¿®’¥Ð’¥Ã’¥Õ’¥¡’¥µ’¥¤’¥º */ //__code echoaccept(int listen_fd, struct sockaddr *caddr, socklen_t *len ); __code echoaccept(int listen_fd, void *caddr, void *len ); //__code echoread(void *ptr); void *echoread(void *ptr); __code conref(); __code confail(); __code echowrite(int conn_fd, char *buf, int rsize); void main() { struct sockaddr_in saddr; /* ’¥µ’¡¼’¥Ð’ÍÑ’¥¢’¥É’¥ì’¥¹’³Ê’Ǽ’¹½’¤’ÂÎ */ struct sockaddr_in caddr; /* ’¥¯’¥é’¥¤’¥¢’¥ó’¥È’ÍÑ’¥¢’¥É’¥ì’¥¹’³Ê’Ǽ’¹½’¤’ÂÎ */ int listen_fd; int conn_fd; //int len = sizeof(struct sockaddr_in); socklen_t len = sizeof(struct sockaddr_in); int rsize; char buf[MAXDATA]; /* ’¼õ’¿®’¥Ð’¥Ã’¥Õ’¥¡ */ /* ’¥½’¥±’¥Ã’¥È’¤Î’À¸’À® */ if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(EXIT_FAILURE); } /* * saddr’¤Î’Ãæ’¿È’¤ò0’¤Ë’¤·’¤Æ’¤ª’¤«’¤Ê’¤¤’¤È’¡¢bind()’¤Ç’¥¨’¥é’¡¼’¤¬’µ¯’¤³’¤ë’¤³’¤È’¤¬’¤¢’¤ë */ bzero((char *)&saddr, sizeof(saddr)); /* ’¥½’¥±’¥Ã’¥È’¤Ë’¥¢’¥É’¥ì’¥¹’¤È’¥Ý’¡¼’¥È’¤ò’·ë’¤Ó’¤Ä’¤±’¤ë */ saddr.sin_family = PF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(PORT); if (bind(listen_fd, (struct sockaddr *)&saddr, len) < 0) { perror("bind"); exit(EXIT_FAILURE); } /* ’¥Ý’¡¼’¥È’¤òListen’¤¹’¤ë */ if (listen(listen_fd, SOMAXCONN) < 0) { perror("listen"); exit(EXIT_FAILURE); } printf("Start Listening Port : %d...\n", PORT); // goto echoread((void *)&conn_fd); goto echoaccept(listen_fd, (void *)&caddr, (void *)&len); } //__code echoaccept(int listen_fd, struct sockaddr *caddr, socklen_t *len ) __code echoaccept(int listen_fd, void *caddr, void *len ) { int conn_fd; if((conn_fd = accept(listen_fd, (struct sockaddr *)caddr, (socklen_t *)len)) < 0){ perror("accept"); exit(EXIT_FAILURE); }else{ pthread_t thread; pthread_create( &thread, NULL, (void *)echoread, (void *)&conn_fd); goto echoaccept(listen_fd, caddr, len); } } //__code echoread(void *ptr) void *echoread(void *ptr) { int conn_fd = *(int*)ptr; char buf[MAXDATA]; /* ’¼õ’¿®’¥Ð’¥Ã’¥Õ’¥¡ */ int rsize; rsize = recv(conn_fd, buf, MAXDATA, 0); if(rsize == 0 ){/* if connection refused */ goto conref(); }else if(rsize == -1){ goto confail(); }else{ goto echowrite(conn_fd, buf, rsize); } } __code conref() { printf("connection refused"); pthread_cancel(pthread_self()); } __code confail() { perror("recv"); exit(EXIT_FAILURE); } __code echowrite(int conn_fd, char *buf, int rsize) { write(conn_fd, buf, rsize); goto echoread((void *)&conn_fd); }