自学内容网 自学内容网

TCP和UDP通讯

机械臂

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <myhead.h>
#define SER_PORT 8888
#define SER_IP "192.168.122.68" //服务端
 
//TCP客户端
int main(int argc, const char *argv[])
{
//创建套接字
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd == -1)
{
perror("socket error");
return -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);
//链接服务器
if(connect(sfd,(struct sockaddr*)&sin,sizeof(sin)) == -1)
{
perror("connect error");
return -1;
}
//收发数据
char rbuf[5]={0xff,0x02,0x00,0xa6,0xff}; //红色手臂
unsigned char wbuf[5]={0xff,0x02,0x01,0x00,0xff}; //蓝色手臂
char key = 0; //接收按键
while(1)
{
printf("请输入:");
scanf("%c",&key);
getchar(); //吸收回车
//对输入的字符进行多分支选择
switch(key)
{
case 'w':
rbuf[3] += 2;
if(rbuf[3] >= 90)
{
rbuf[3] = 90;
}
send(sfd,rbuf,sizeof(rbuf),0);
break;
case 's':
rbuf[3] += 2;
if(rbuf[3] >= 90)
{
rbuf[3] = 90;
}
send(sfd,rbuf,sizeof(rbuf),0);
break;
case 'a':
wbuf[3] += 2;
if(wbuf[3] >= 90)
{
wbuf[3] = 90;
}
send(sfd,wbuf,sizeof(wbuf),0);
break;
case 'd':
wbuf[3] += 2;
if(wbuf[3] >= 90)
{
wbuf[3] = 90;
}
send(sfd,wbuf,sizeof(wbuf),0);
break;
default:printf("error\n");
}
//判断退出
if(key == 'q' || key == 'Q')
{
break; //结束循环
}
}

//关闭套接字
close(sfd);
 
return 0;
}

 


原文地址:https://blog.csdn.net/wanyu_l/article/details/135615395

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!