// 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 */
|