#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <linux/input.h>
#include <sys/stat.h>
#include <fcntl.h>
#define CL_IP "192.168.124.157"
#define CL_PORT 6666
int main(int argc, const char *argv[])
{
//创建流式套接字文件
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("socket");
return -1;
}
printf("创建流式套接字文件成功\n");
/*//填充服务器的地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);*/
//允许端口号被快速重复使用
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
fprintf(stderr, "line:%d ", __LINE__);
perror("setsockopt");
return -1;
}
//填充服务器的地址信息,给connect函数连接服务器的时候使用
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(CL_PORT);
sin.sin_addr.s_addr = inet_addr(CL_IP);
//连接服务器
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
fprintf(stderr, "line:%d ", __LINE__);
perror("connect");
return -1;
}
printf("connect success\n");
//打开键盘驱动文件:/dev/input/event1
int fd = open("/dev/input/event1",O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
struct input_event ev;
char buf[5]={0xff,0x02,0x00,-90,0xff};
unsigned char abuf[5]={0xff,0x02,0x01,45,0xff};
//ssize_t res;
/* while(1)
{
printf("请输入数据\n");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] ='\0';
*/
//发送
char c;
while(1)
{
if(read(fd,&ev,sizeof(ev)) < 0)
{
perror("read");
return -1;
}
switch(ev.code*ev.value)
{
case 17:
buf[3]+=5;
if(buf[3] > 90)
buf[3] = -90;
break;
case 31:
buf[3]-=5;
if(buf[3]<-90)
buf[3]=90;
break;
case 30:
abuf[3]-=5;
if(abuf[3]<-180)
abuf[3]=180;
break;
case 32:
abuf[3]+=5;
if(abuf[3]<0)
abuf[3]=180;
break;
default:
continue;
}
if(send(cfd,buf,sizeof(buf),0) < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("send");
return -1;
}
printf("send success\n");
if(send(cfd,abuf,sizeof(abuf),0) < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("send");
return -1;
}
printf("send success\n");
}
/* //接受
bzero(buf,sizeof(buf));
res = recv(cfd,buf,sizeof(buf),0);
if(res < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("recv");
return -1;
}
else if(0 == res)
{
printf("服务器下线\n");
break;
}
printf("cfd=%d : %s __%d__\n",cfd,buf,__LINE__);
}*/
//关闭文件描述符
close(cfd);
return 0;
}
TCP客户端控制机械臂
最新推荐文章于 2024-09-26 15:00:08 发布