#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <linux/input.h>
#define SER_IP "192.168.125.136"
#define SER_PORT 8888
#define CLI_IP "192.168.203.255"
#define CLI_PORT 9999
int main(int argc, const char *argv[])
{
//1、创建用于通信的套接字文件描述符
int cfd = socket(AF_INET, SOCK_STREAM, 0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
printf("socket success cfd = %d\n", cfd); //3
//设置端口号快速重用
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
printf("端口号快速重用成功\n");
//2、绑定IP和端口号
//对于客户端而言,如果没有绑定IP地址和端口号
//那么系统回默认将当前ip地址与一个随机的端口号进行绑定
//如果客户端绑定了端口号,那么使用的就是自己绑定的
//2.1 填充地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET; //协议族
cin.sin_port = htons(CLI_PORT); //客户端端口号
cin.sin_addr.s_addr = inet_addr(CLI_IP); //客户端ip地址
//2.2 绑定工作
if(bind(cfd, (struct sockaddr*)&cin, sizeof(cin)) == -1)
{
perror("bind error");
return -1;
}
printf("bind success\n");
//3、连接服务器
//3.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);//服务器IP
//3.2 连接服务器
if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin))==-1)
{
perror("connect error");
return -1;
}
printf("connect success\n");
//4、数据收发
char rbuf[5] = {0xff, 0x02, 0x00, 0x00, 0xff};
unsigned char bbuf[5] = {0xff, 0x02, 0x01, 0x00, 0xff};
int key = open("/dev/input/event1",O_RDONLY);
if(key == -1)
{
perror("open");
return -1;
}
while(1)
{
struct input_event kb;
read(key,&kb,sizeof(struct input_event));
printf("type=%d code=%d value =%d\n",kb.type,kb.code,kb.value);
switch(kb.value*kb.code)
{
case 30://a 蓝减
{if(bbuf[3]>0)
{
bbuf[3]-=3;
send(cfd,bbuf,sizeof(rbuf),0);
}
break;
}
case 31://s 红减
{if(rbuf[3]>-90)
{
rbuf[3]-=3;
send(cfd,rbuf,sizeof(rbuf),0);
}
break;
}
case 32://d 蓝加
{if(bbuf[3]<180)
{
bbuf[3]+=3;
send(cfd,bbuf,sizeof(bbuf),0);
}
break;
}
case 17://w 红加
{if(rbuf[3]<=90)
{
rbuf[3]+=3;
send(cfd,rbuf,sizeof(rbuf),0);
}
break;
}
}
}
//5、关闭套接字
close(key);
close(cfd);
return 0;
}
4.15作业
最新推荐文章于 2024-10-03 13:36:06 发布