tcpip_sample.c

00001 /*
00002   TCP/IP 通信の Linux 実装
00003   Satofumi KAMIMURA
00004   $Id$
00005 */
00006 
00007 #include <sys/types.h>
00008 #include <sys/socket.h>
00009 #include <netinet/in.h>
00010 #include <arpa/inet.h>
00011 #include <sys/poll.h>
00012 #include <unistd.h>
00013 #include <stdio.h>
00014 #include <stdlib.h>
00015 
00016 
00017 int tcpip_recv(struct pollfd *nfds, char *data, int size, int timeout) {
00018   int fd = nfds->fd;
00019   int filled = 0;
00020   int n;
00021 
00022   while (filled < size) {
00023     if (poll(nfds, 1, timeout) == 0) {
00024       break;                    // timeout
00025     }
00026     n = read(fd, &data[filled], size - filled);
00027     if (n <= 0) {
00028       break;
00029     }
00030     filled += n;
00031   }
00032   return filled;
00033 }
00034 
00035 
00036 
00037 int main(int argc, char *argv[]) {
00038   int sockfd;
00039   struct sockaddr_in address;
00040   struct pollfd nfds;
00041   int len;
00042   int result;
00043   char ch;
00044 
00045   // サーバに接続
00046   sockfd = socket(AF_INET, SOCK_STREAM, 0);
00047   address.sin_family = AF_INET;
00048   address.sin_addr.s_addr = inet_addr("localhost");
00049   address.sin_port = htons(9314);
00050   len = sizeof(address);
00051 
00052   result = connect(sockfd, (struct sockaddr*)&address, len);
00053   if (result < 0) {
00054     perror("connect");
00055     exit(1);
00056   }
00057 
00058   // poll() 用の設定
00059   nfds.fd = sockfd;
00060   nfds.events = POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL;
00061   nfds.revents = 0;
00062 
00063   // 書き込み
00064   ch = 'a';
00065   result = write(sockfd, &ch, 1);
00066   printf("write: %d\n", result);
00067 
00068   // 読み出し
00069   ch = 'a' + 1;
00070   result = tcpip_recv(&nfds, &ch, 1, 1000);
00071   printf("recv: %d\n", result);
00072   if (result > 0) {
00073     printf("%c\n", ch);
00074   }
00075 
00076   return 0;
00077 }
00078 

Generated on Mon Apr 13 22:52:05 2009 by  doxygen 1.5.7.1