华清远见嵌入式学习——网络编程——作业2

利用TCP通信协议,创建客户端,实现对机械臂的控制

#include 

#define SERIP "192.168.114.103"
#define SERPORT 8888

int main(int argc, const char *argv[])
{
	//创建用于通信的套接字
	int cfd = socket(AF_INET,SOCK_STREAM,0);
	if(cfd == -1)
	{
		perror("socket error");
		return -1;
	}

	//连接服务器
	  //定义服务器地址信息结构体
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(SERPORT);
	sin.sin_addr.s_addr = inet_addr(SERIP);
	  //连接
	if(connect(cfd,(struct sockaddr *)&sin,sizeof(sin)) == -1)
	{
		perror("connect error");
		return -1;
	}
	
	//向服务器发送数据或接收服务器返回数据
	char rbuf[5] = {0xff,0x02,0x00,0x00,0xff};
	unsigned char bbuf[5] = {0xff,0x02,0x01,0x00,0xff};
	
	//向服务器发送机械臂初始设置
	send(cfd,rbuf,sizeof(rbuf),0);		
	send(cfd,bbuf,sizeof(bbuf),0);		
	char key;
	while(1)
	{	
		puts("请在下方所有空白处输入key:");
		key = getchar();
		getchar();
		switch(key)
		{
			case 'w':
			{
				rbuf[2] = 0x00;
				printf("红色臂角度增加\n");
				rbuf[3] = rbuf[3] + 3;
				if(rbuf[3] > 90)
				{
					rbuf[3] = 90;
					continue;
				}
				
			}
			break;
			case 's':
			{
				rbuf[2] = 0x00;
				printf("红色臂角度减小\n");
				rbuf[3] = rbuf[3] - 3;
				if(rbuf[3] < -90)
				{
					rbuf[3] = -90;
					continue;
				}
			
			}
			break;
			case 'd':
			{
				bbuf[2] = 0x01;
				printf("蓝色臂角度增加\n");
				bbuf[3] = bbuf[3] + 3;
				if(bbuf[3] > 180)
				{
					bbuf[3] = 180;
					continue;
				}
			
			}
			break;
			case 'a':
			{
				bbuf[2] = 0x01;
				printf("蓝色臂角度减小\n");
				bbuf[3] = bbuf[3] - 3;
				if(bbuf[3] < 0)
				{
					bbuf[3] = 0;
					continue;
				}
			
			}
			break;
			case 'q':
			{
				rbuf[3] = 0;
				bbuf[3] = 0;
			}
			break;
			default:
			{
				continue;
			}
			break;
		}

		if(send(cfd,rbuf,sizeof(rbuf),0) == -1)
		{
			perror("send error");
			return -1;
		}
		if(send(cfd,bbuf,sizeof(bbuf),0) == -1)
		{
			perror("send error");
			return -1;
		}
		printf("数据发送成功\n");
		
	}
	//关闭套接字
	close(cfd);
	return 0;
}

代码效果动图:

你可能感兴趣的:(学习,网络,php)