소켓 네트워크 프로 그래 밍 - 채 팅 프로그램 (1)

26425 단어 socket
이 른 시간 에 APUE 와 UNPv 1 을 보고 네트워크 프로 그래 밍 을 이 해 했 지만 보기 만 했 을 뿐 구체 적 인 실천 이 없 었 다. 지금 할 일이 없 을 때 네트워크 프로 그래 밍 을 실천 해 보 자.블 로 그 를 써 서 저장 하면 나중에 사용 할 때 찾 을 수 있 습 니 다.
이번 채 팅 프로그램 은 교체 개발 됐다.한 걸음 한 걸음 다른 기능 으로 수정 되 는 채 팅 프로그램 이다.
서버 서버 와 클 라 이언 트 client
  
일대일, server 와 client 는 한 마디 씩 채 팅 합 니 다.
몇 개의 함수 gethostby name () 을 설명 합 니 다. 이 함 수 는 이전에 말 한 적 이 있 으 면 더 이상 말 하지 않 습 니 다.
소켓 함수
  #include
  int socket(int domain, int type, int protocol);    //반환 값: 성공 하면 파일 (소켓) 설명 자 를 되 돌려 주 고 오류 가 발생 하면 되 돌려 줍 니 다 - 1
connect 함수
  #include
  int connect(int sockfd, const struct sockaddr *addr, socklen_t len);   //반환 값: 성공 하면 0 을 되 돌려 주 고, 오류 가 발생 하면 되 돌려 줍 니 다 - 1
bind 함수
  #include
  int bind(int sockfd, const struct sockaddr *addr, socklen_t len);   //반환 값: 성공 하면 0 을 되 돌려 주 고, 오류 가 발생 하면 되 돌려 줍 니 다 - 1
listen 함수
  #include
  int listen(int sockfd, int backlog);  //반환 값: 성공 하면 0 을 되 돌려 주 고 오류 가 발생 하면 - 1 을 되 돌려 줍 니 다. backlog 는 연결 요청 수량 을 표시 합 니 다.
accept 함수
  #include
  int accept(int socdfd, struct sockaddr *restrict addr, socklen_t * restrict len); //성공 하면 파일 (socket 소켓) 설명 자 를 되 돌려 주 고 오류 가 발생 하면 되 돌려 줍 니 다 - 1
recv 함수
  #include
  ssize_t recv(int sockfd, void *buf, size_t nbytes, int flags);  //반환 값: 바이트 로 계 산 된 메시지 길이 입 니 다. 사용 가능 한 메시지 가 없 거나 상대방 이 순서대로 끝 났 으 면 0 으로 돌아 갑 니 다. 오류 가 발생 하면 되 돌아 갑 니 다 - 1
send 함수
  #include
  ssize_t send(int sockfd, const void *buf, size_t nbytes, int flags);  //반환 값: 성공 하면 보 낸 바이트 수 를 되 돌려 주 고 오류 가 발생 하면 되 돌려 줍 니 다 - 1
fgets 함수
  #include
  char *fgets(char *s, int size, FILE *stream);
 함 수 를 소개 한 후 바로 코드 를 붙 입 니 다.
  client.c
 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 #include <errno.h>

 4 #include <string.h>

 5 #include <netdb.h> //for gethostbyname

 6 #include <sys/types.h>

 7 #include <sys/socket.h>

 8 #include <netinet/in.h>

 9 #include <arpa/inet.h>

10 

11 #define MAX_BUF 4096

12 #define SERVER_PORT 12138

13 

14 

15 int main(int argc,char *argv[])

16 {

17     int sockfd;//socket

18     char sendBuf[MAX_BUF],recvBuf[MAX_BUF];

19     int sendSize,recvSize;//                 

20     struct hostent * host;

21     struct sockaddr_in servAddr;

22     char username[32];

23     char * p;

24 

25     if(argc != 3)

26     {

27         perror("use: ./client [hostname] [username]");

28         exit(-1);

29     }

30     p=username;

31     strcpy(p,argv[2]);

32     printf("username:%s
",username); 33 host=gethostbyname(argv[1]); 34 if(host==NULL) 35 { 36   perror("fail to get host by name."); 37 exit(-1); 38 } 39 printf("Success to get host by name ...
"); 40 41 // socket 42 if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) 43 { 44   perror("fail to establish a socket"); 45   exit(1); 46 } 47 printf("Success to establish a socket...
"); 48 49 /*init sockaddr_in*/ 50 servAddr.sin_family=AF_INET; 51 servAddr.sin_port=htons(SERVER_PORT); 52 servAddr.sin_addr=*((struct in_addr *)host->h_addr); 53 bzero(&(servAddr.sin_zero),8); 54 55 /*connect the socket*/ 56 if(connect(sockfd,(struct sockaddr *)&servAddr,sizeof(struct sockaddr_in))==-1) 57 { 58   perror("fail to connect the socket"); 59   exit(1); 60 } 61 printf("Success to connect the socket...
"); 62 63 //send-recv 64 while(1) 65 { 66 printf("Input:"); 67 fgets(sendBuf,MAX_BUF,stdin); 68 send(sockfd,sendBuf,strlen(sendBuf),0); 69 memset(sendBuf,0,sizeof(sendBuf)); 70 recv(sockfd,recvBuf,MAX_BUF,0); 71 printf("Server:%s
",recvBuf); 72 memset(recvBuf,0,sizeof(recvBuf)); 73 } 74 75 return 0; 76 }

  server.c
  1 #include <stdio.h>

  2 #include <stdlib.h>

  3 #include <errno.h>

  4 #include <string.h>

  5 #include <netdb.h>

  6 #include <sys/types.h>

  7 #include <sys/socket.h>

  8 #include <sys/time.h>

  9 #include <sys/un.h>

 10 #include <sys/ioctl.h>

 11 #include <sys/wait.h>

 12 #include <netinet/in.h>

 13 #include <arpa/inet.h>

 14 

 15 

 16 #define SERVER_PORT 12138

 17 #define BACKLOG 20

 18 #define MAX_CON_NO 10

 19 #define MAX_DATA_SIZE 4096

 20 

 21 int main(int argc,char *argv[])

 22 {

 23     struct sockaddr_in serverSockaddr,clientSockaddr;

 24     char sendBuf[MAX_DATA_SIZE],recvBuf[MAX_DATA_SIZE];

 25     int sendSize,recvSize;

 26     int sockfd,clientfd;

 27     int on=1;

 28     int sinSize=0;

 29     char username[32];

 30 

 31     if(argc != 2)

 32     {

 33         printf("usage: ./server [username]
"); 34 exit(1); 35 } 36 strcpy(username,argv[1]); 37 printf("username:%s
",username); 38 39 /*establish a socket*/ 40 if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1) 41 { 42 perror("fail to establish a socket"); 43 exit(1); 44 } 45 printf("Success to establish a socket...
"); 46 47 /*init sockaddr_in*/ 48 serverSockaddr.sin_family=AF_INET; 49 serverSockaddr.sin_port=htons(SERVER_PORT); 50 serverSockaddr.sin_addr.s_addr=htonl(INADDR_ANY); 51 bzero(&(serverSockaddr.sin_zero),8); 52 53 setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); 54 55 /*bind socket*/ 56 if(bind(sockfd,(struct sockaddr *)&serverSockaddr,sizeof(struct sockaddr))==-1) 57 { 58 perror("fail to bind"); 59 exit(1); 60 } 61 printf("Success to bind the socket...
"); 62 63 /*listen on the socket*/ 64 if(listen(sockfd,BACKLOG)==-1) 65 { 66 perror("fail to listen"); 67 exit(1); 68 } 69 70 /*accept a client's request*/ 71 if((clientfd=accept(sockfd,(struct sockaddr *)&clientSockaddr, &sinSize))==-1) 72 { 73 perror("fail to accept"); 74 exit(1); 75 } 76 printf("Success to accpet a connection request...
"); 77 printf(" %s join in!
",inet_ntoa(clientSockaddr.sin_addr)); 78 while(1) 79 { 80 /*receive datas from client*/ 81 if((recvSize=recv(clientfd,recvBuf,MAX_DATA_SIZE,0))==-1) 82 { 83 perror("fail to receive datas"); 84 exit(1); 85 } 86 printf("%s
",recvBuf); 87 memset(recvBuf,0,MAX_DATA_SIZE); 88 89 /*send datas to client*/ 90 printf("Server:"); 91 fgets(sendBuf,MAX_DATA_SIZE,stdin); 92 if((sendSize=send(clientfd,sendBuf,strlen(sendBuf),0))!=strlen(sendBuf)) 93 { 94 perror("fail to send datas"); 95 exit(1); 96 } 97 printf("Success to send datas
"); 98 memset(sendBuf,0,MAX_DATA_SIZE); 99 } 100 101 return 0; 102 }

 이 코드 들 은 모두 비교적 간단 하고 상세 한 설명 은 인터넷 에 모두 있 으 니 여 기 는 더 이상 말 하지 않 겠 다.
  
본문 주소:  http://www.cnblogs.com/wunaozai/p/3870156.html

좋은 웹페이지 즐겨찾기