当前位置:   article > 正文

C语言网络编程客户端和服务器之间的通信(tcp)_mfc 客户端和服务器传送文件

mfc 客户端和服务器传送文件

客户端

  1. #include <stdio.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #define SERVPORT 5000
  7. int main(int argc,char ** argv)
  8. {
  9. int sockfd,n;
  10. struct sockaddr_in servaddr,cliaddr;
  11. char sendline[1000];//发送缓冲区大小
  12. char recvline[1000];
  13. if(argc != 2)
  14. {
  15. printf("usage:server address!\n");
  16. exit(0);
  17. }
  18. sockfd = socket(AF_INET,SOCK_STREAM,0);
  19. bzero(&servaddr,sizeof(servaddr));
  20. servaddr.sin_family = AF_INET;
  21. servaddr.sin_port = htons(SERVPORT);
  22. servaddr.sin_addr.s_addr = inet_addr(argv[1]);
  23. connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
  24. while(fgets(sendline,1000,stdin) != NULL)
  25. {
  26. sendto(sockfd,sendline,strlen(sendline),0,
  27. (struct sockaddr *)&servaddr,sizeof(servaddr));
  28. n = recvfrom(sockfd,recvline,1000,0,NULL,NULL);
  29. recvline[n] = '\0';
  30. fputs(recvline,stdout);
  31. }
  32. close(sockfd);
  33. return 0;
  34. }

服务器

  1. #include <stdio.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <arpa/inet.h>
  7. #include <unistd.h>
  8. #define SERVPORT 5000
  9. int main()
  10. {
  11. int listenfd, connfd, n;
  12. struct sockaddr_in servaddr, cliaddr;
  13. socklen_t clilen;
  14. char msg[1000];
  15. listenfd = socket(AF_INET, SOCK_STREAM, 0);
  16. bzero(&servaddr, sizeof(servaddr));
  17. servaddr.sin_family = AF_INET;
  18. servaddr.sin_port = htons(SERVPORT);
  19. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  20. bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
  21. listen(listenfd, 100);
  22. while (1) //多个客户端
  23. {
  24. clilen = sizeof(cliaddr);
  25. connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
  26. for (;;) //多次会话
  27. {
  28. n = recvfrom(connfd, msg, 1000, 0, (struct sockaddr *)&cliaddr, &clilen);
  29. if (0 == n)
  30. {
  31. printf("client offline!\n");
  32. break;
  33. }
  34. sendto(connfd, msg, n, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
  35. printf("--------------------------------\n");
  36. msg[n] = '\0';
  37. printf("received the following:\n");
  38. printf("%s\n", msg);
  39. printf("--------------------------------------\n");
  40. }
  41. close(connfd);
  42. }
  43. close(listenfd);
  44. return 0;
  45. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/144105
推荐阅读
相关标签
  

闽ICP备14008679号