1、新建socketContrl.c文件---->添加Socket服务器功能
#include <stdio.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include "InputCommand.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int socketGetCommand(struct InputCommander *socketMes)
{
int c_fd;
int n_read = 0;
struct sockaddr_in c_addr;
memset(&c_addr,0,sizeof(struct sockaddr_in));
int clen = sizeof(struct sockaddr_in);
c_fd = accept(socketMes->sfd,(struct sockaddr *)&c_addr,&clen);
n_read = read(c_fd,socketMes->command,sizeof(socketMes->command));
if(n_read == -1){
perror("read");
}else if(n_read > 0){
printf("\nget: %d\n",n_read);
}else{
printf("client quit\n");
}
return n_read;
}
int socketInit(struct InputCommander *socketMes,char *ipAdress,char *port)
{
int s_fd;
struct sockaddr_in s_addr; //定义一个为套接字添加信息的结构体
memset(&s_addr,0,sizeof(struct sockaddr_in)); //数据的清空处理
s_fd = socket(AF_INET,SOCK_STREAM,0); //创建一个服务端套接字
if(s_fd == -1){
printf("socket create fail\n");
}
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(atoi(socketMes->port));
inet_aton(socketMes->ipAddress,&s_addr.sin_addr);
bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in)); //为套接字添加信息
listen(s_fd,10);
printf("socket Server listening.....\n");
socketMes->sfd = s_fd;
return s_fd;
}
struct InputCommander socketContrl = {
.commandName = "socketServer",
.command = {'\0'},
.port = "8128",
.ipAddress = "19
文章评论