IO网络2.0

思维导图

机械臂

#include 
#include 
#include 
#include 
#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;
}

你可能感兴趣的:(c语言)