设为首页 加入收藏

TOP

ubuntu环境下实现 多线程的socket(tcp) 通信(二)
2019-03-12 00:09:12 】 浏览:452
Tags:ubuntu 环境 实现 线程 socket tcp 通信
// Author: jiujue 3 // Created Time: 2019年03月09日 星期六 13时00分05秒 4 5 #include<stdio.h> 6 #include<string.h> 7 #include<stdlib.h> 8 #include<time.h> 9 #include<math.h> 10 #include <unistd.h> 11 #include <sys/socket.h> 12 #include <arpa/inet.h> 13 14 15 int main(int argc, const char* argv[]) 16 { 17 18 if(argc < 3) 19 { 20 printf("eg: ./app Ip Port\n"); 21 exit(1); 22 } 23 int port = atoi(argv[2]); 24 25 int fd = socket(AF_INET, SOCK_STREAM, 0); 26 if(-1 == fd) 27 { 28 perror("socket error"); 29 exit(1); 30 } 31 32 struct sockaddr_in serv; 33 34 serv.sin_port = htons(port); 35 serv.sin_family = AF_INET; 36 inet_pton(AF_INET, argv[1], &serv.sin_addr.s_addr); 37 38 socklen_t len = sizeof(serv); 39 int res = connect(fd,(struct sockaddr *) &serv, len); 40 if(-1 == res) 41 { 42 perror("connect error"); 43 exit(1); 44 } 45 printf("Connectt server successful!!\n"); 46 47 while(1) 48 { 49 printf("Please input string\n>>"); 50 char buf[1024]; 51 fgets(buf,sizeof(buf),stdin); 52 write(fd, buf, strlen(buf)); 53 printf("send buf: %s\n",buf); 54 len = read(fd,buf,(buf)); 55 if(len > 0) 56 { 57 printf("Recv buf: %s\n",buf); 58 }else if(len == 0) 59 { 60 printf("Serer disconnect \n"); 61 break; 62 } 63 else if(-1 == len) 64 { 65 perror("Read errror"); 66 exit(1); 67 }else 68 { 69 printf("I no now\n"); 70 } 71 } 72 73 close(fd); 74 return 0 ; 75 } View Code

 

 结语:有问题欢迎提在下方 ,本人在校学生,时间较为充裕, 有时间会回复的。

/* 原创文章 转载请附上原链接: https://www.cnblogs.com/jiujue/p/10513859.html   */

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇#leetcode刷题之路18-四数之和 下一篇内核中对文件的读写操作

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目