思维导图
机械臂
#include<head.h>
#define SER_PORT 8888 //服务器端口号
#define SER_IP "192.168.122.88" //服务器IP地址
#define CLI_PORT 7777 //客户端端口号
#define CLI_IP "192.168.122.22" //客户端IP地址
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("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、给套接字绑定地址信息
//2.1 填充地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET; //地址族
sin.sin_port = htons(CLI_PORT); //端口号网络字节序
sin.sin_addr.s_addr = inet_addr(CLI_IP); //IP地址网络字节序
//2.2 绑定工作
if(bind(cfd, (struct sockaddr*)&sin, sizeof(sin)) == -1)
{
perror("bind error");
return -1;
}
printf("bind success _%d_\n", __LINE__);
*/
//4、连接服务器
//4.1 填充要连接的服务器地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET; //IPv4通信
cin.sin_port = htons(SER_PORT); //服务器端口号
cin.sin_addr.s_addr = inet_addr(SER_IP); //服务器的主机地址
//4.2 连接服务器
if(connect(cfd, (struct sockaddr*)&cin, sizeof(cin)) == -1)
{
perror("connect error");
return -1;
}
printf("connect success _%d_\n", __LINE__);
char buf[5]="";
buf[0]=0xff;
buf[1]=0x02;
buf[2]=0x00;
buf[3]=0x00;
buf[4]=0xff;
char red=buf[3];
char blue=buf[3];
char cbuf=0;
while(1)
{
cbuf=getchar();
getchar();
if(cbuf=='w')
{
buf[2]=0x00;
red=red+1;
buf[3]=red;
send(cfd,buf,sizeof(buf),0);
}else if(cbuf=='s')
{
buf[2]=0x00;
red=red-1;
buf[3]=red;
send(cfd,buf,sizeof(buf),0);
}else if(cbuf=='a')
{
buf[2]=0x01;
blue-=1;
buf[3]=blue;
send(cfd,buf,sizeof(buf),0);
}else if(cbuf=='d')
{
buf[2]=0x01;
blue+=1;
buf[3]=blue; //6、关闭套接字
//关闭连接的套接字
send(cbuf,buf,sizeof(buf),0);
}
}
close(cfd);
return 0;
}
UDP
#include<head.h>
int main(int argc, const char *argv[])
{
//创建套接字文件
int sfd = socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("sfd error");
return -1;
}
//绑定
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(8888);
sin.sin_addr.s_addr=inet_addr("192.168.122.22");
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("bind error");
return -1;
}
//数据的收发
char buf[128]="";
struct sockaddr_in cin;
socklen_t socklen=sizeof(cin);
while(1)
{
bzero(buf,sizeof(buf));
recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&socklen);
printf("读取的消息为:%s\n",buf);
strcat(buf,"*_*");
if(sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,socklen)==-1)
{
perror("write error");
return -1;
}
}
close(sfd);
return 0;
}