回射服务器即客户端发送一段数据给服务器,服务器再将这段数据原封不动的发送给客户端,原理很简单,原理图如下:
以TCP协议为例,客户端、服务器代码如下:
**
服务器:
**
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main()
{struct sockaddr_in server_sockaddr;memset(&server_sockaddr,0,sizeof(server_sockaddr));server_sockaddr.sin_family=AF_INET;server_sockaddr.sin_port=htons(5188);server_sockaddr.sin_addr.s_addr=htonl(INADDR_ANY);//创建一个socketint sockid=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);const int on=1;//设置重复利用端口,如果不设置在频繁调试时会出现端口被占用情况,导致bind失败setsockopt(sockid,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));//bindif(bind(sockid,(struct sockaddr *)&server_sockaddr,sizeof(server_sockaddr))<0){printf("bind\n");return 0;}//listenif(listen(sockid,SOMAXCONN)<0){printf("listen\n");return 0;}//获得连接的客户端信息struct sockaddr_in client_sockaddr;socklen_t client_socklen=sizeof(client_sockaddr);//acceptint client_sock=accept(sockid,(struct sockaddr *)&client_sockaddr,&client_socklen);//打印所连接客户端ip及端口printf("ip=%s,port=%d\n",inet_ntoa(client_sockaddr.sin_addr),ntohs(client_sockaddr.sin_port));char receive[100]={0};int r_size=0;while(1){//获取时间,即服务器接收数据的时间time_t timep;time(&timep);memset(receive,0,sizeof(receive));//读取数据,如果没有读到就等待,因为此时read阻塞,如果客户端关闭read立即返回0if((r_size=read(client_sock,receive,sizeof(receive)))==0){break;}fputs(ctime(&timep),stdout);fputs(receive,stdout);printf("\n");//将读取到的数据在发给客户端write(client_sock,receive,r_size);}close(client_sock);close(sockid);return 0;
}
客户端:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{struct sockaddr_in sock;memset(&sock,0,sizeof(sock));sock.sin_family=AF_INET;sock.sin_port=htons(5188);sock.sin_addr.s_addr=inet_addr("127.0.0.1");//创建一个socketint sockid=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);socklen_t socklen=sizeof(sock);//connectconnect(sockid,(struct sockaddr *)&sock,socklen);char send[100]={0};char receive[100]={0};while(1){printf("发送: ");//从标准输入获取一段数据fgets(send,sizeof(send),stdin);//将这段数据发送给服务器write(sockid,send,strlen(send));printf("接受: ");//读取来自服务器传回来的数据read(sockid,receive,sizeof(receive));fputs(receive,stdout);//将这两个数组清零memset(receive,0,strlen(receive));memset(send,0,strlen(send));}close(sockid);return 0;
}