3.14网络编程

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"      //客户端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;
	}
	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--90
	unsigned 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;
		}else
			printf("输入错误,请重新输入\n");
	}

//5、关闭套接字
close(cfd);

return 0;
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值