TCP机械臂调试代码
#include<myhead.h>
#include <termios.h>
#define SER_PORT 8888 //服务器端口号
#define SER_IP "192.168.117.36" //服务器IP
#define CLI_PORT 9000 //客户端端口号
#define CLI_IP "192.168.141.134" //客户端IPint main(int argc, const char *argv[])
{//1、创建用于通信的套接字文件描述符int cfd = socket(AF_INET, SOCK_STREAM, 0);if(cfd == -1){perror("socket error");return -1;}printf("%d cfd = %d\n",__LINE__, cfd); //3//重用int reuse = 1;if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1){perror("setsockopt");return -1;}printf("重用成功\n");/*//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");return -1;}printf("%d bind success\n",__LINE__);*///3、连接服务器struct sockaddr_in sin;sin.sin_family = AF_INET; //地址族sin.sin_port = htons(SER_PORT); //端口号sin.sin_addr.s_addr = inet_addr(SER_IP); //ip地址// 连接if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin))==-1){perror("connect");return -1;}printf("%d connect success\n",__LINE__);//4、数据收发char rbuf[5] = {0xff, 0x02, 0x00, 0x00, 0xff};//red -90--0--90unsigned char ybuf[5] = {0xff, 0x02, 0x01, 0x00, 0xff};//blue 0--90--180//发送给服务器当做初始值send(cfd, rbuf, sizeof(rbuf), 0);sleep(1);send(cfd, ybuf, sizeof(ybuf), 0);struct termios old,new;tcgetattr(STDIN_FILENO,&old);new=old;new.c_lflag&=~(ICANON);tcsetattr(STDIN_FILENO,TCSANOW,&new);//实现getchar()直接吸入字符char key = 0;while(1){key = getchar();if((key|32) == 'w'){rbuf[3] +=10;//10度偏移if(rbuf[3]>=90){rbuf[3] = 90;}printf("__%#x^w^\n",rbuf[3]);send(cfd, rbuf, sizeof(rbuf), 0);}else if((key|32) == 's'){rbuf[3] -=10;//10度偏移if(rbuf[3]<=-90){rbuf[3] = -90;}printf("__%#x^s^\n",rbuf[3]);send(cfd, rbuf, sizeof(rbuf), 0);}else if((key|32) == 'd'){ybuf[3] +=10;//10度偏移if(ybuf[3]>=180){ybuf[3] = 180;}printf("__%#x^d^\n",ybuf[3]);send(cfd, ybuf, sizeof(ybuf), 0);}else if((key|32) == 'a'){ybuf[3] -=10;//10度偏移if(ybuf[3]<=0){ybuf[3] = 0;}printf("__%#x^a^\n",ybuf[3]);send(cfd, ybuf, sizeof(ybuf), 0);}else if((key|32) == 'q'){printf("__退出\n");break;}elseprintf("输入错误,请重新输入\n");}//5、关闭套接字
close(cfd);return 0;
}