#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#define ERR_MSG(msg) \
do \
{ \
fprintf(stderr, "_%d_:", __LINE__); \
perror(msg); \
} while (0)
#define IP "192.168.31.40"
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("%d\n", sfd);
//填充ip 和端口地址到地址信息结构体中,实际结构体是友地址族决定;
//AF_INET_________man ip
struct sockaddr_in sin;
sin.sin_family = AF_INET; //地址族必须式制定
sin.sin_port = htons(8888); //端口号的网络字节序:1204-49151
sin.sin_addr.s_addr = inet_addr(IP); //ubuntu 的本机IP:
//链接服务器
if (connect(sfd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
ERR_MSG("connect");
return -1;
}
printf("connect success\n");
char buf[5] = {0xff, 0x02, 0x00, 0x00, 0xff};
ssize_t res;
printf("请输入>>>>>>>\n");
while (1)
{
//接收
char c;
scanf("%c", &c);
getchar();
switch (c)
{
case 'w':
buf[2] = 0x00;
buf[3] += 1;
if (-90 >= buf[3] || 90 <= buf[3])
{
buf[3] = 0x00;
}
if (send(sfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
break;
case 's':
buf[2] = 0x00;
buf[3] += -1;
if (-90 >= buf[3] || 90 <= buf[3])
{
buf[3] = 0x00;
}
if (send(sfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
break;
case 'a':
buf[2] = 0x01;
buf[3] += 1;
if (0 >= buf[3] || 180 <= buf[3])
{
buf[3] = 0x00;
}
if (send(sfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
break;
case 'd':
buf[2] = 0x01;
buf[3] += -1;
if (0 >= buf[3] || 180 <= buf[3])
{
buf[3] = 0x00;
}
if (send(sfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
break;
default:
break;
}
}
close(sfd);
return 0;
}