1 #include2 #include3 #include4 #include5 #include6 #include7 #include8 #include9 /*
10 *tcp服務端-----簡單的網路聊天程式
11 *1 建立socket
12 *2 為socket繫結位址埠
13 *3 開始監聽socket---告訴作業系統,開始接收連線請求,並且處理連線請求
14 *4 接收連線請求-獲取新連線的socket(sip sport dip dport proto)
15 *5 收發資料----recv/send
16 *6 關閉新建socket(程式結束時關閉最開始的socket)
17 * */
18 19
20 int main(int argc,char* argv)
21 26 //1 建立socket
27 int listen_fd=-1;
28 listen_fd=socket(af_inet,sock_stream,0);
29 if(listen_fd<0)
33 struct sockaddr_in lst_addr;
34 lst_addr.sin_family=af_inet;
35 lst_addr.sin_port=htons(atoi(argv[2]));
36 lst_addr.sin_addr.s_addr=inet_addr(argv[1]);
37 38 socklen_t len=sizeof(struct sockaddr_in);
39 //2 為socket繫結位址埠
40 int ret=bind(listen_fd,(struct sockaddr*)&lst_addr,len);
41 42 if(ret<0)
46 //3 開始監聽socket---告訴作業系統,開始接收連線請求,並且處理連線請求
47 if(listen(listen_fd,5)<0)
51 52 while(1)
62 //5 收發資料----recv/send
63 char buff[1024];
64 while(1)else if(ret<0)
73 break;
74 }
75 printf("client say:%s\n",buff);
76 77 char tmp[1024];
78 printf("input:");
79 fflush(stdout);
80 scanf("%s",tmp);
81 send(new_fd,tmp,strlen(tmp),0);
82 }
83 close(new_fd);
84 }
85 //6 關閉新建socket(程式結束時關閉最開始的socket)
86 close(listen_fd);
87 return 0;
88 }
1 #include2 #include3 #include4 #include5 #include6 #include7 #include8 #include9 /*
10 *tcp客戶端-----簡單的網路聊天程式
11 *1 建立socket
13 *3 向服務端發起連線請求 connect()
14 *4 收發資料----recv/send
15 *5 關閉socket
16 * */
17 18 int main(int argc,char *argv)
23 //1 建立socket
24 int sockfd=socket(af_inet,sock_stream,ipproto_tcp);
25 if(sockfd<0)
29 30 struct sockaddr_in ser_addr;
31 ser_addr.sin_family=af_inet;
32 ser_addr.sin_port=htons(atoi(argv[2]));
33 ser_addr.sin_addr.s_addr=inet_addr(argv[1]);
34 35 socklen_t len=sizeof(struct sockaddr_in);
36 //2 向伺服器發起連線
37 int ret=connect(sockfd,(struct sockaddr*)&ser_addr,len);
38 if(ret<0)
42 //3 收發資料----recv/send
43 while(1);
45 printf("input:");
46 fflush(stdout);
47 scanf("%s",buff);
48 //通過socket傳送資料
49 send(sockfd,buff,strlen(buff),0);
50 //接收資料
51 char tmp[1024]=;
52 recv(sockfd,tmp,1023,0);
53 printf("server say:%s\n",tmp);
54 55 }
56 57 //5 關閉socket
58 close(sockfd);
59 return 0;
60 }
TCP客戶端與服務端通訊
客戶端 include include include include include in.h include include include include define maxline 1024 int main int argc,char ar 建立socketfd socketfd soc...
TCP客戶端服務端demo
服務端程式 include include include include include include include int main 列印握手成功的客戶端 struct sockaddr in servaddr socklen t nservlen sizeof servaddr getso...
TCP連線實現 客戶端 服務端 通訊
客戶端 client.c include include include include include include include include define max buf 512 int main int argc,char argv 設定伺服器位址結構體 bzero server ad...