1. 机械臂
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <myhead.h>
#define CLI_PORT 6667 //本机的端口号
#define CLI_IP "192.168.125.79" //本机的IP
#define SER_PORT 8888 //服务器的端口号
#define SER_IP "192.168.125.202" //服务器的IP
int main(int argc, const char *argv[])
{
//创建套接字,用于通信
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd<0)
{
perror("socket error");
return -1;
}
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1)
{
perror("setsockopt error");
return -1;
}
//绑定IP地址和端口号
struct sockaddr_in cinfo;
cinfo.sin_family=AF_INET;
cinfo.sin_port=htons(CLI_PORT);
cinfo.sin_addr.s_addr=inet_addr(CLI_IP);
if(bind(cfd,(struct sockaddr*)&cinfo,sizeof(cinfo))<0)
{
perror("bind error");
return -1;
}
//连接到服务器
struct sockaddr_in sinfo;
sinfo.sin_family=AF_INET;
sinfo.sin_port=htons(SER_PORT);
sinfo.sin_addr.s_addr=inet_addr(SER_IP);
if(connect(cfd,(struct sockaddr*)&sinfo,sizeof(sinfo))<0)
{
perror("connect error");
return -1;
}
printf("connect success \n");
//发送信息
char str[5]={0xff,0x02,0x00,0x00,0xff};
char c;
char blue=0x00;
char red=0x00;
send(cfd,str,sizeof(str),0);
while(1)
{
printf("please input a/w/s/d\n");
scanf("%c",&c);
getchar();
switch(c)
{
case 'a' :
case 'A' :
str[2]=0x01;
blue-=0x01;
str[3]=blue;
break;
case 'd' :
case 'D' :
str[2]=0x01;
blue+=0x01;
str[3]=blue;
break;
case 's' :
case 'S' :
str[2]=0x00;
red-=0x01;
str[3]=red;
break;
case 'w' :
case 'W' :
str[2]=0x00;
red+=0x01;
str[3]=red;
break;
default: break;
}
ssize_t res=send(cfd,str,sizeof(str),0);
if(res<0)
{
perror("while error");
return -1;
}
if(res==0)
{
printf("serve off\n");
break;
}
}
//关闭套接字
close(cfd);
return 0;
}
本地不知道为啥,连接不上,防火墙的问题