思维导图
大小臂
#include<myhead.h>
#define SER_PORT 8888 //服务器端口号
#define SER_IP "192.168.125.37" //服务器ip地址
#define CLI_PORT 6666 //客户端的端口号
#define CLI_IP "192.168.125.50" //客户端IP地址
int main(int argc, const char *argv[])
{
//1、创建用于通信的套接字文件描述符
int cfd = socket(AF_INET, SOCK_STREAM, 0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
//将端口号快速重用函数
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1)
{
perror("setsockopt error");
return -1;
}
//2、绑定
//2.1 填充地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLI_PORT);
cin.sin_addr.s_addr = inet_addr(CLI_IP);
//2.2 绑定
if(bind(cfd, (struct sockaddr*)&cin, sizeof(cin)) == -1)
{
perror("bind error");
return -1;
}
//3、连接服务器
//3.1 填充服务器地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
//3.2 连接
if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) == -1)
{
perror("connect error");
return -1;
}
printf("连接成功\n");
//4、收发数据
//定义大臂小臂
char flag = 0;
char rbuf[5] = {0xff, 0x02, 0x00, 0, 0xff};
unsigned char bbuf[5] = {0xff, 0x02, 0x01, 0, 0xff};
while(1)
{
printf("请输入>>>");
scanf("%c",&flag);
getchar();
switch(flag)
{
case 'w':
case 'W':
{
rbuf[3] += 3;
if(rbuf[3] >= 90)
{
rbuf[3] = 90;
}
send(cfd, rbuf, sizeof(rbuf), 0);
}break;
case 's':
case 'S':
{
rbuf[3] -= 3;
if(rbuf[3] <= -90)
{
rbuf[3] = -90;
}
send(cfd, rbuf, sizeof(rbuf), 0);
}break;
case 'd':
case 'D':
{
bbuf[3] += 3;
if(bbuf[3] >= 180)
{
bbuf[3] = 180;
}
send(cfd, bbuf, sizeof(bbuf), 0);
}break;
case 'a':
case 'A':
{
bbuf[3] -= 3;
if(bbuf[3] <= 0)
{
bbuf[3] = 0;
}
send(cfd, bbuf, sizeof(bbuf), 0);
}break;
}
}
//5、关闭套接字
close(cfd);
return 0;
}