思维导图
作业
TCP机械臂测试 通过w(红色臂角度增大)s(红色臂角度减小)d(蓝色臂角度增大)a(蓝色臂角度减小)按键控制机械臂
代码
#include<myhead.h>
#define SER_PORT 8888
#define SER_IP "192.168.0.108"
#define CLI_PORT 6666
#define CLI_IP "192.168.190.128"
int main(int argc, char const *argv[])
{
//创建
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
printf("cfd = %d\n",cfd);
//端口号快速重用
int reuse = 1;
if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) == -1)
{
perror("setsockopt error");
return -1;
}
printf("端口号快速重启成功\n");
//绑定
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLI_PORT);
cin.sin_addr.s_addr = inet_addr(CLI_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");
//初始化机械臂
int a = 0x00;
int b = 0x00;
char rbuf[5] = {0xff,0x02,0x00,a,0xff};
char bbuf[5] = {0xff,0x02,0x01,b,0xff};
send(cfd,rbuf,sizeof(rbuf),0);
sleep(1);
send(cfd,bbuf,sizeof(bbuf),0);
//读取并判断输入的指令
while(1)
{
char dir = getchar();
getchar();
if(dir == 'w')
{
a += 5;
}
else if(dir == 'a')
{
b -= 5;
}
else if(dir == 's')
{
a -= 5;
}
else if(dir == 'd')
{
b += 5;
}
else
{
printf("error\n");
continue;
}
char rbuf[5] = {0xff,0x02,0x00,a,0xff};
char bbuf[5] = {0xff,0x02,0x01,b,0xff};
//发送给服务器
send(cfd,rbuf,sizeof(rbuf),0);
sleep(1);
send(cfd,bbuf,sizeof(bbuf),0);
}
close(cfd);
return 0;
}