#include<myhead.h>
#define SERPORT 8888
#define SERIP "192.168.125.91"
#define CLIPORT 6213
#define CLIIP "192.168.125.93"
int main(int argc, const char *argv[])
{
//1、创建用于通信的套接字
int cfd = -1;
if((cfd=socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket error");
return -1;
}
printf("cfd = %d\n", cfd); //3
//将端口号快速重用
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
//2、可以绑定也可以不绑定
//2.1 填充地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLIPORT);
cin.sin_addr.s_addr = inet_addr(CLIIP);
//2.2 绑定
if(bind(cfd, (struct sockaddr *)&cin, sizeof(cin)) == -1)
{
perror("bind error");
return -1;
}
//3、连接服务器
//3.1 填充服务器地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET; //地址族
sin.sin_port = htons(SERPORT); //服务器端口号
sin.sin_addr.s_addr = inet_addr(SERIP); //服务器IP地址
//3.2 连接服务器
if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) == -1)
{
perror("connect error");
return -1;
}
printf("connect success\n");
//4、数据收发
char wbuf[5] = {0xff,0x02,0x00,0x00,0xff};
unsigned char buf[5] = {0xff,0x02,0x01,0x00,0xff};
send(cfd, wbuf, sizeof(wbuf), 0);
send(cfd, buf, sizeof(buf), 0);
char value;
while(1)
{
//输入内容
value=getchar();
switch (value)
{
case 'w':
case 'W':
wbuf[3]+=10;
if(-90<=wbuf[3]<=90)
{
send(cfd, wbuf, sizeof(wbuf), 0);
}
else
{
wbuf[3]-=10;
}
break;
case 's':
case 'S':
wbuf[3]-=10;
if(-90<=wbuf[3]<=90)
{
send(cfd, wbuf, sizeof(wbuf), 0);
}
else
{
wbuf[3]+=10;
}
break;
case 'a':
case 'A':
buf[3]-=10;
if(0<=buf[3]<=180)
{
send(cfd, buf, sizeof(buf), 0);
}
else
{
buf[3]+=10;
}
break;
case 'd':
case 'D':
buf[3]+=10;
if(0<=buf[3]<=180)
{
send(cfd, buf, sizeof(buf), 0);
}
else
{
buf[3]-=10;
}
break;
}
}
//5、关闭套接字
close(cfd);
return 0;
}
?