赞
踩
客户端
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdlib.h>
- #include <string.h>
-
- #define SERVPORT 5000
-
-
- int main(int argc,char ** argv)
- {
- int sockfd,n;
- struct sockaddr_in servaddr,cliaddr;
- char sendline[1000];//发送缓冲区大小
- char recvline[1000];
-
- if(argc != 2)
- {
- printf("usage:server address!\n");
- exit(0);
- }
-
- sockfd = socket(AF_INET,SOCK_STREAM,0);
-
- bzero(&servaddr,sizeof(servaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htons(SERVPORT);
- servaddr.sin_addr.s_addr = inet_addr(argv[1]);
-
-
- connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
-
- while(fgets(sendline,1000,stdin) != NULL)
-
- {
- sendto(sockfd,sendline,strlen(sendline),0,
- (struct sockaddr *)&servaddr,sizeof(servaddr));
-
-
- n = recvfrom(sockfd,recvline,1000,0,NULL,NULL);
-
-
- recvline[n] = '\0';
-
- fputs(recvline,stdout);
- }
- close(sockfd);
-
- return 0;
- }
服务器
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdlib.h>
- #include <string.h>
- #include <arpa/inet.h>
- #include <unistd.h>
-
- #define SERVPORT 5000
-
- int main()
- {
- int listenfd, connfd, n;
- struct sockaddr_in servaddr, cliaddr;
- socklen_t clilen;
- char msg[1000];
-
- listenfd = socket(AF_INET, SOCK_STREAM, 0);
-
- bzero(&servaddr, sizeof(servaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htons(SERVPORT);
- servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
-
- bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
-
- listen(listenfd, 100);
-
- while (1) //多个客户端
- {
- clilen = sizeof(cliaddr);
-
- connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
-
- for (;;) //多次会话
- {
- n = recvfrom(connfd, msg, 1000, 0, (struct sockaddr *)&cliaddr, &clilen);
-
- if (0 == n)
- {
- printf("client offline!\n");
- break;
- }
-
- sendto(connfd, msg, n, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
-
- printf("--------------------------------\n");
-
- msg[n] = '\0';
-
- printf("received the following:\n");
-
- printf("%s\n", msg);
-
- printf("--------------------------------------\n");
- }
-
- close(connfd);
- }
-
- close(listenfd);
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。