本人介绍:
本人为长春理工大学人工智能学院20级机器人工程专业学生,最近由于长春疫情返回家中上网课,由于在自学TCPsocket通信中遇到一个问题,关于如何在公网中实现TCP通信,于是查阅资料后知道要想实现公网TCP通信就得有一个公网域名,于是我打算申请一个云服务器,用这个云服务器作为中转站,即可实现TCPsocket公网通信,于是在寻找云服务器的过程中我了解到了阿里云开发者飞天计划。
接下来我说一下在使用阿里云服务器的过程中遇到的问题。由于我使用云服务器主要是做TCP服务端,所以这就涉及到了TCP协议,以及IP和端口,在端口上面我是吃了大亏的,之前把程序写好后运行一直报错,一开始以为是端口防火墙问题,重新设置了很多次安全组以及防火墙,但一直没能解决问题,后来才发现原来是从Linux虚拟机复制粘贴过来的时候格式出了问题。然后我选择用Xshell将Linux虚拟机的文件传到windows,然后通过Xshell远程登陆阿里云,将文件传到云服务器上,再次编译,成功运行!
通过本次的实践,我掌握了云服务器的基本操作,加深了我对Linux命令行的理解,并且对TCP协议有了更深的认识,以后无论是学习UDP或者HTTP都能更快速的上手,接下来展示一下我做的TCP公网通信用阿里云服务器做转发,一个客户端为LinuxQT上位机,另外一个客户端为esp8266,通过qt上位机控制led灯的开闭。
客户端代码:
include "stdio.h"
include "stdlib.h"
include "assert.h"
include "string.h"
include "sys/types.h"
include "sys/socket.h"
include "arpa/inet.h"
include "netinet/in.h"
include "unistd.h"
include "pthread.h"
int ret;
int i=0;
int c_fd[2];
struct sockaddr_in saddr,caddr;
pthread_t t1;
pthread_t t2;
char BUFF1[256];
char BUFF2[256];
int read_1;
int read_2;
int param=100;
void thread1(void arg)
{
while(1)
{
memset(BUFF1,0,sizeof(BUFF1));
printf("Client1 address is %s\n",inet_ntoa(caddr.sin_addr));
read_1=read(c_fd[0],BUFF1,255);
if(read_1==-1) {printf("read client1 is error");}
else { printf("I read client1:%s\n",BUFF1);
write(c_fd[1],BUFF1,strlen(BUFF1));
}
}
}
void thread2(void arg)
{
while(1)
{
memset(BUFF2,0,sizeof(BUFF2));
printf("client2 address is %s\n",inet_ntoa(caddr.sin_addr));
read_2=read(c_fd[1],BUFF2,255);
if(read_2==-1) {printf("read client2 is error");}
else { printf("I read client2:%s\n",BUFF2);
write(c_fd[0],BUFF2,strlen(BUFF2));
}
}
}
int main()
{
int sockfd=socket(AF_INET,SOCK_STREAM,0);
assert(sockfd!=-1);
// struct sockaddr_in saddr,caddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(8000);
saddr.sin_addr.s_addr=inet_addr("172.17.124.48");
int res=bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
assert(res!=-1);
res=listen(sockfd,5);
assert(res!=0);
int len=sizeof(caddr);
while(1)
{
if(i==0)
{
c_fd[i]=accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c_fd[i]<0){continue;}
i=1;
printf("I am client1\n");
}else {
c_fd[i]=accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c_fd[i]<0){continue;}
i=2;
printf("I am client2\n");
}
if(c_fd[0]==-1)
{printf("client1 is connect error");}
else
{ ret=pthread_create(&t1,NULL,thread1,(void *)¶m);
assert(ret!=-1);
}
if(c_fd[1]==-1)
{printf("client2 is connect error");}
else
{ ret =pthread_create(&t2,NULL,thread2,(void *)¶m);assert(res!=-1);}
}
return 0;
}
qt上位机:
运行效果: