欢迎来到天天文库
浏览记录
ID:50831944
大小:119.25 KB
页数:6页
时间:2020-03-15
《一个C语言socket小程序.docx》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、C语言socket简介socket协议三次握手与结束连接客户端代码:[cpp] viewplaincopy1.#include 2.#include 3.#include //for bzero 4. 5.#include //for socketaddr_in 6.#include 7.#include 8.#include 9. 10.#define PORT 5050 //端口号
2、11.#define MAXLEN_FOR_DATA 1024//数据的最大长度 12. 13.int main(){ 14. 15. int clientfd;// 套接字 16. int len, ret; 17. char buf[MAXLEN_FOR_DATA]; 18. 19. struct sockaddr_in serveraddr; 1. 2. //建立套接口 3. clientfd = socket(AF_INET, SOCK_STREAM, 0); 4. if (cl
3、ientfd == -1){ 5. fprintf(stderr, "Failed: socket() "); 6. goto exit; 7. } 8. printf("Sucessed: socket()"); 9. 10. 11. //****连接******** 12. serveraddr.sin_family = AF_INET; 13. serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 14. serv
4、eraddr.sin_port = htons(PORT); 15. len = sizeof(serveraddr); 16. ret = connect(clientfd, (struct sockaddr*)&serveraddr, len); 17. if (ret == -1){ 18. fprintf(stderr, "Failed: connect()"); 19. goto exit; 20. } 21. printf("Sucessed: connect() "); 22.
5、 23. sprintf(buf, "%s ", "Hello World!"); 24. ret = send(clientfd, (void*)buf, strlen(buf), 0); 25. if (ret <= 0){ 26. fprintf(stderr, "Failed: send()"); 27. goto exit; 28. } 29. printf("Sucessed: send()"); 30. 31. 32. exit: 33. c
6、lose(clientfd); 34. clientfd = -1; 35. return 0; 36.} 服务器:[cpp] viewplaincopy1.#include 2.#include 3.#include //for bzero 4. 5.#include //for socketaddr_in 6.#include 7.#include 8.#include 7、no.h> 9. 10.#define PORT 5050 11.#define LEN_FOR_LISTEN_QUEUE 5 12.#define MAXLEN_FOR_DATA 1024 13. 14.int main(){ 15. 16. // 17. int serverfd, clientfd;//套接字 18. int len; 19. int ret; 20. char buf[MAXLEN_
7、no.h> 9. 10.#define PORT 5050 11.#define LEN_FOR_LISTEN_QUEUE 5 12.#define MAXLEN_FOR_DATA 1024 13. 14.int main(){ 15. 16. // 17. int serverfd, clientfd;//套接字 18. int len; 19. int ret; 20. char buf[MAXLEN_
此文档下载收益归作者所有