网络编程day3作业

1.TCP客户端实现机械臂操作

代码:

//机械臂客户端

#include 

#define PORT 8888
#define IP "192.168.125.73"

int main(int argc, const char *argv[])
{ 
	//1.创建套接字
	int cfd=socket(AF_INET,SOCK_STREAM,0);

	//2.连接服务端
	struct sockaddr_in ser;
	ser.sin_family=AF_INET;
	ser.sin_port=htons(PORT);
	ser.sin_addr.s_addr=inet_addr(IP);

	connect(cfd,(struct sockaddr*)&ser,sizeof(ser));
	printf("已连接服务器!\n");

	//3.收发数据
	char red[5]={0xff,0x02,0x00,0x00,0xff};
	unsigned char blue[5]={0xff,0x02,0x01,0x00,0xff};
	char value=0;

	while(1)
	{
		//从终端输入数据
		value=getchar();
		switch(value)
		{
		case 'w':  //红色机械臂增大
			{
				red[3] += 5;
				if(red[3] >= 90)
					red[3]=90;

				send(cfd,red,sizeof(red),0);
			} 
			break;
		case 's':  //红色机械臂减小
			{
				red[3] -= 5;
				if(red[3] <= -90)
					red[3]= -90;

				send(cfd,red,sizeof(red),0);
			}
			break;
		case 'a':  //蓝色机械臂增大
			{
				blue[3] += 5;
				if(blue[3] >= 180)
					blue[3]=180;

				send(cfd,blue,sizeof(blue),0);
			}
			break;
		case 'd':  //蓝色机械臂减小
			{
				blue[3] -= 5;
				if(blue[3] <= 0)
					blue[3]=0;

				send(cfd,blue,sizeof(blue),0);
			}
			break;
		}
	}

	//4.关闭套接字
	close(cfd);

	return 0;
}

你可能感兴趣的:(网络,linux)