3.14 网络编程

#include 
#define SER_PORT 8888
#define SER_IP "192.168.117.71"
int main(int argc, const char *argv[])
{
	//创建客户端
	int cfd=socket(AF_INET,SOCK_STREAM,0);
	if(cfd==-1)
	{
	perror("socket error");
	return -1;
	}
	printf("scoket success cfd=%d\n",cfd);
	//设置端口号快速重用
	int reuse = 1;
	if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) ==-1)
	{
		perror("setsockopt 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(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
	{
	perror("connet error"); 
	return -1;
	}
	printf("连接成功\n");
	//重置机械臂
	char buf_red[5]={0xff,0x02,0x00,0x00,0xff};
	unsigned char buf_blue[5]={0xff,0x02,0x01,0x00,0xff};
	send(cfd,buf_red,sizeof(buf_red),0);
	sleep(1);
	send(cfd,buf_blue,sizeof(buf_blue),0);
	//收发数据
	char ctl=0;
	while(1)
	{
	scanf("%c",&ctl);
	getchar();
	switch(ctl)
	{
	case 'w':
	case 'W':
		{
			buf_red[3]++;
			if(buf_red[3] >= 90)
			{
				buf_red[3] = 90;
			}
			send(cfd, buf_red, sizeof(buf_red), 0);
		}
		break;
	case 's':
	case 'S':
		{
			buf_red[3]--;
			if(buf_red[3] <= -90)
			{
				buf_red[3] = -90;
			}
			send(cfd, buf_red, sizeof(buf_red), 0);
		}
		break;
	case 'a':
	case 'A':
		{
			buf_blue[3]++;
			if(buf_blue[3] >= 180)
			{
				buf_blue[3] = 180;
			}
			send(cfd, buf_blue, sizeof(buf_blue), 0);
		}
		break;
	case 'd':
	case 'D':
		{
			buf_blue[3]++;
			if(buf_blue[3] <= 0)
			{
				buf_blue[3] = 0;
			}
			send(cfd, buf_blue, sizeof(buf_blue), 0);
		}
		break;
	case 'q':
	case 'Q':
		{
		goto END;
		}
	}
END:
	close(cfd);
	}
	return 0;
}

你可能感兴趣的:(tcp/ip,udp)