TCP
1. 头文件
1 #pragma once 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <strings.h> 8 #include <string.h> 9 #include <linux/in.h> 10 11 #define IP "192.168.2.150" 12 #define PORT 9999 13 #define SIZE 128
2. client_tcp
1 #include "net.h" 2 3 int main(void) 4 { 5 //1.创建套接字 6 int fd = socket(AF_INET,SOCK_STREAM,0); 7 if(fd<0){ 8 perror("socket failed"); 9 exit(1); 10 } 11 12 13 //2.初始服务器地址 14 struct sockaddr_in cli; 15 cli.sin_family = AF_INET; 16 cli.sin_port = htons(PORT); 17 cli.sin_addr.s_addr=inet_addr(IP); 18 19 20 //3.发起连接请求 21 if( connect(fd,(struct sockaddr*)&cli,sizeof(cli))<0 ){ 22 perror("connect failed"); 23 exit(1); 24 } 25 26 27 //4.写 28 char buf[SIZE]; 29 while(1){ 30 bzero(buf,SIZE); 31 printf("please input: "); 32 fgets(buf,SIZE,stdin); 33 write(fd,buf,strlen(buf)); 34 if(strncmp(buf,"quit",4)==0) 35 break; 36 } 37 38 39 //5.关闭 40 close(fd); 41 42 return 0 ; 43 }
3.server_tcp
1 #include "net.h" 2 3 int main(void) 4 { 5 //1.创建套接字 6 int fd = socket(AF_INET,SOCK_STREAM,0); 7 if(fd<0){ 8 perror("socket failed"); 9 exit(1); 10 } 11 12 13 //2.初始本地地址 14 struct sockaddr_in ser; 15 ser.sin_family = AF_INET; 16 ser.sin_port = htons(PORT); 17 ser.sin_addr.s_addr=inet_addr(IP); 18 19 20 //3.绑定 21 if( bind(fd,(struct sockaddr*)&ser,sizeof(ser))<0 ){ 22 perror("bind failed"); 23 exit(1); 24 } 25 26 27 //4.监听 28 if( listen(fd,5)<0 ){ 29 perror("listen failed"); 30 exit(1); 31 } 32 33 34 //5.接收 35 int newfd; 36 if( (newfd=accept(fd,NULL,NULL))<0 ){ 37 perror("accept failed"); 38 exit(1); 39 } 40 41 42 //6.读 43 char buf[SIZE]; 44 while(1){ 45 bzero(buf,SIZE); 46 int ret = read(newfd,buf,SIZE); 47 if(ret<0){ 48 perror("read failed"); 49 exit(1); 50 } 51 else if(ret==0) 52 break; 53 else 54 printf("server : %s",buf); 55 if(strncmp(buf,"quit",4)==0) 56 break; 57 } 58 59 //7.关闭 60 close(fd); 61 close(newfd); 62 63 64 return 0 ; 65 }
测试:
success !