一、实现虚拟机械臂控制
#include<myhead.h>
#define SER_PORT 8888 //服务器端口号
#define SER_IP "192.168.0.126" //服务器ip地址
#define CLI_PORT 5555 //客户端端口号
#define CLI_IP "192.168.0.133" //客户端地址
int main(int argc, const char *argv[])
{
//创建套接字文件
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
printf("cfd = %d\n",cfd); //3
//绑定IP地址和端口号
//填充地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET; //通信域
cin.sin_port = htons(CLI_PORT); //端口号
cin.sin_addr.s_addr = inet_addr(CLI_IP); //ip地址
//绑定工作
if(bind(cfd,(struct sockaddr*)&cin,sizeof(cin))==-1)
{
perror("bind error");
return -1;
}
printf("bind success\n");
//连接到服务器
//服务器端地址
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("connect error");
return -1;
}
printf("成功连接到服务端\n");
//控制机械臂
//初始化机械臂
char redbuf[5] = {0xff,0x02,0x00,0x50,0xff};
char bluebuf[5] = {0xff,0x02,0x01,0x00,0xff};
send(cfd,redbuf,sizeof(redbuf),0);
sleep(1);
send(cfd,bluebuf,sizeof(redbuf),0);
char buf = 0;
//实现使用“wasd”操控机械臂
while(1)
{
//先清空buf
buf = 0;
//输入
scanf("%c",&buf);
getchar();
if(buf == 'W')
{
redbuf[3]++;
if(redbuf[3]>90)
{
printf("请更换方向,该方向已移动到最值\n");
redbuf[3]--;
}else{
send(cfd,redbuf,sizeof(redbuf),0);
}
}else if(buf == 'S')
{
redbuf[3]--;
if(redbuf[3]<-90)
{
printf("请更换方向,该方向已移动到最值\n");
redbuf[3]++;
}else{
send(cfd,redbuf,sizeof(redbuf),0);
}
}else if(buf =='A')
{
bluebuf[3]++;
if(bluebuf[3]>180)
{
printf("请更换方向,该方向已移动到最值\n");
bluebuf[3]--;
}else{
send(cfd,bluebuf,sizeof(bluebuf),0);
}
}else if(buf == 'D')
{
bluebuf[3]--;
if(bluebuf[3]<0)
{
printf("请更换方向,该方向已移动到最值\n");
bluebuf[3]++;
}else{
send(cfd,bluebuf,sizeof(bluebuf),0);
}
}else if(buf == 'q')
{
break;
}
}
//关闭文件描述符
close(cfd);
return 0;
}
二、思维导图