TCP机械臂
#include <myhead.h>
#define SER_PORT 8888
#define SER_IP "192.168.125.64"
#define CLI_PORT 6666
#define CLI_IP "192.168.125.32"
int main(int argc, const char *argv[])
{
//1.创建套接字
int cfd = socket(AF_INET,SOCK_STREAM,0/*IPPROTO_TCP*/);
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;
}
//2.绑定(随意)
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");
//printf("bind success %s %s %d\n",__FILE__,__func__,__LINE__);
//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 bufred[5]={0xff,0x02,0x00,-90,0xff};
char bufblue[5]={0xff,0x02,0x01,0,0xff};
while(1)
{
char ch;
printf("请输入w&a&s&d:");
scanf("%c",&ch);
getchar();
if(ch == 'w')
{
bufred[3]+=5;
if(bufred[3]>90)
{
bufred[3]=90;
continue;
}
}
else if(ch == 's')
{
bufred[3]-=5;
if(bufred[3]<-90)
{
bufred[3]=-90;
continue;
}
}
else if(ch == 'a')
{
bufblue[3]-=5;
if(bufblue[3]<0)
{
bufblue[3]=0;
continue;
}
}
else if(ch == 'd')
{
bufblue[3]+=5;
if(bufblue[3]>180)
{
bufblue[3]=180;
continue;
}
}else{
puts("输入有误");
}
//发送给服务器
send(cfd,bufred,sizeof(bufred),0);
send(cfd,bufblue,sizeof(bufblue),0);
printf("发送成功\n");
}
//5.关闭套接字
close(cfd);
return 0;
}