c语言socket双向通信+一服务端对多客户端通信

时间:2023-01-24 22:15:42

任务

在完成socket客户端对服务端的通信以后,又让我搞双向通信,然后又是让我用app去控制gpio口的高低变化.努力了三天,从socket的学习到多线程的学习,一步一步的完成了任务,测试从app到服务器在到小板上的数据流全部打通.下班之前记录一下.

思路

socket双向通信使用的方法是服务端开启服务等客户端连接上以后开辟一个线程,然后把客户端套接字client_sockfd传递过去,输入数据后发送给客户端.反之亦然.
一服务端对多客户端的通信采用select.参考博客见:http://blog.csdn.net/ctrl_qun/article/details/52524086 作者写的非常棒,讲解的也很全面,继续研读中.对它的代码进行了部分改进.添加了对客户端上传的数据下发到所有的客户端,这个是我项目中的需求.然后添加了一个头文件.因为有些即用即初始化的参数,所以需要使用c99的标准去编译.

gcc -std=c99 client.c -o client

双向通信

/*代码里面有部分我对驱动程序的相关控制*/
/*socket端*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <linux/ioctl.h>
#include<fcntl.h>
#include<sys/stat.h>
#define MAXBUF 512

#define DEV_IOC_MAGIC '0xee' //定义幻数


#define DEV_IOCPRINT _IO(DEV_IOC_MAGIC, 1)
#define DEV_IO_HIGH _IO(DEV_IOC_MAGIC, 2)
#define DEV_IO_LOW _IO(DEV_IOC_MAGIC, 3)

#define DEV_IOC_MAXNR 3

char send_buf[MAXBUF+1];
int fd;
void *thread(void *x)
{
int cmd;
char buf[BUFSIZ];
int new_fd = *((int*)x);
while(recv(new_fd,buf,BUFSIZ,0)>0)
{
//int len=recv(new_fd,buf,BUFSIZ,0);
if(strcmp(buf,"1")==0)
{
printf("<--- Call DEV_IO_HIGH --->\n");
cmd = DEV_IO_HIGH;
if (ioctl(fd, cmd) < 0)
{
printf("Call cmd DEV_IO_HIGH fail\n");
}
printf("NOW,GPIO is High.\n");
}
if(strcmp(buf,"0")==0)
{
printf("<--- Call DEV_IO_LOW --->\n");
cmd = DEV_IO_LOW;
if (ioctl(fd, cmd) < 0)
{
printf("Call cmd DEV_IO_LOW fail\n");
}
printf("NOW,GPIO is Low.\n");
}
printf("client:received:%s\n",buf);
}
/*while(1)
{
bzero(send_buf, MAXBUF + 1);
scanf("%s",send_buf);
send(new_fd, send_buf, strlen(send_buf), 0); //第 4 步 向套接字中写入字符串
}*/

return NULL;
}

void open_dev()
{
fd = open("/dev/dsx", O_RDWR);
if(fd < 0)
printf("/dev/dsx is open fail!\n");
}

int main(int argc, char *argv[])
{
int client_sockfd;
int len;
struct sockaddr_in remote_addr; //服务器端网络地址结构体
char buf[BUFSIZ]; //数据传送的缓冲区
memset(&remote_addr,0,sizeof(remote_addr)); //数据初始化--清零
remote_addr.sin_family=AF_INET; //设置为IP通信
remote_addr.sin_addr.s_addr=inet_addr("0.0.0.0");//服务器IP地址
remote_addr.sin_port=htons(8000); //服务器端口号
open_dev();
/*创建客户端套接字--IPv4协议,面向连接通信,TCP协议*/
if((client_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}

/*将套接字绑定到服务器的网络地址上*/
if(connect(client_sockfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0)
{
perror("connect");
return 1;
}
printf("connected to server\n");
//len=recv(client_sockfd,buf,BUFSIZ,0);//接收服务器端信息
// buf[len]='\0';
//printf("%s",buf); //打印服务器端信息
//新建一个线程来进行发送操作.
pthread_t ntid;
pthread_create(&ntid,NULL,thread,&client_sockfd);
/*循环的发送接收信息并打印接收信息--recv返回接收到的字节数,send返回发送的字节数*/
while(1)
{
//printf("Enter string to send:");
scanf("%s",buf);
if(!strcmp(buf,"quit"))
break;
len=send(client_sockfd,buf,strlen(buf),0);
//len=recv(client_sockfd,buf,BUFSIZ,0);
//buf[len]='\0';
//printf("received:%s\n",buf);
printf("client:send ok.\n");
}
close(client_sockfd);//关闭套接字
return 0;
}
/*服务端*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#define MAXBUF 512
char recv_buf[MAXBUF+1];
char link_state=1;
int aa;
void *fun(int x)
{
int new_fd=x;//(int)(*((int*)x));
while(1)
{
bzero(recv_buf, MAXBUF + 1);
scanf("%s",recv_buf);
int len = send(new_fd, recv_buf, sizeof(recv_buf) , 0);
printf("server:send ok\n");
if(len<=0)
break;
}
exit(0);
}


int main(int argc, char *argv[])
{
int server_sockfd;//服务器端套接字
int client_sockfd;//客户端套接字
int len;
struct sockaddr_in my_addr; //服务器网络地址结构体
struct sockaddr_in remote_addr; //客户端网络地址结构体
int sin_size;
char buf[BUFSIZ]; //数据传送的缓冲区
memset(&my_addr,0,sizeof(my_addr)); //数据初始化--清零
my_addr.sin_family=AF_INET; //设置为IP通信
my_addr.sin_addr.s_addr=INADDR_ANY;//服务器IP地址--允许连接到所有本地地址上
my_addr.sin_port=htons(8000); //服务器端口号

/*创建服务器端套接字--IPv4协议,面向连接通信,TCP协议*/
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}

/*将套接字绑定到服务器的网络地址上*/
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}

/*监听连接请求--监听队列长度为5*/
listen(server_sockfd,5);

sin_size=sizeof(struct sockaddr_in);

/*等待客户端连接请求到达*/
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept");
return 1;
}
printf("accept client %s\n",inet_ntoa(remote_addr.sin_addr));
aa=client_sockfd;//可以直接传递client_sockfd.
//创建线程为了给客户端发送数据
pthread_t ntid;
int a = pthread_create(&ntid,NULL,fun,aa);
if(a=0)
printf("ok\n");
/*接收客户端的数据并将其发送给客户端--recv返回接收到的字节数,send返回发送的字节数*/
while((recv(client_sockfd,buf,BUFSIZ,0))>0)
{
printf("server:recvived:%s\n",buf);
}
close(client_sockfd);
close(server_sockfd);
return 0;
}

一服务端对多客户端

/*client端*/


#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include"client_gpio.h"
#define BUFFER_SIZE 1024

int main(int argc, const char * argv[])
{
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(11332);
server_addr.sin_addr.s_addr = inet_addr("0.0.0.0");
bzero(&(server_addr.sin_zero), 8);

int server_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if(server_sock_fd == -1)
{
perror("socket error");
return 1;
}
char recv_msg[BUFFER_SIZE];
char input_msg[BUFFER_SIZE];

if(connect(server_sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) == 0)
{
fd_set client_fd_set;
struct timeval tv;
open_dev();//打开驱动的设备节点.无则删除
while(1)
{
tv.tv_sec = 20;
tv.tv_usec = 0;
FD_ZERO(&client_fd_set);
FD_SET(STDIN_FILENO, &client_fd_set);
FD_SET(server_sock_fd, &client_fd_set);

select(server_sock_fd + 1, &client_fd_set, NULL, NULL, &tv);
if(FD_ISSET(STDIN_FILENO, &client_fd_set))
{
bzero(input_msg, BUFFER_SIZE);
fgets(input_msg, BUFFER_SIZE, stdin);
if(send(server_sock_fd, input_msg, BUFFER_SIZE, 0) == -1)
{
perror("发送消息出错!\n");
}
}
if(FD_ISSET(server_sock_fd, &client_fd_set))
{
bzero(recv_msg, BUFFER_SIZE);
long byte_num = recv(server_sock_fd, recv_msg, BUFFER_SIZE, 0);
if(byte_num > 0)
{
if(byte_num > BUFFER_SIZE)
{
byte_num = BUFFER_SIZE;
}
recv_msg[byte_num] = '\0';
if(strcmp(recv_msg,"open")==0)//控制设备的相关函数,可删除
{
set_gpio_high();
}
if(strcmp(recv_msg,"close")==0)//控制设备的相关函数,可删除
{
set_gpio_low();
}
printf("服务器:%s\n", recv_msg);
}
else if(byte_num < 0)
{
printf("接受消息出错!\n");
}
else
{
printf("服务器端退出!\n");
exit(0);
}
}
}
}
return 0;
}
/*server端*/

#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include <sys/select.h>
#define BACKLOG 5 //完成三次握手但没有accept的队列的长度
#define CONCURRENT_MAX 8 //应用层同时可以处理的连接
#define SERVER_PORT 11332
#define BUFFER_SIZE 1024
#define QUIT_CMD ".quit"
int client_fds[CONCURRENT_MAX];
int main(int argc, const char * argv[])
{
char input_msg[BUFFER_SIZE];
char recv_msg[BUFFER_SIZE];
//本地地址
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr("0.0.0.0");
bzero(&(server_addr.sin_zero), 8);
//创建socket
int server_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if(server_sock_fd == -1)
{
perror("socket error");
return 1;
}
//绑定socket
int bind_result = bind(server_sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if(bind_result == -1)
{
perror("bind error");
return 1;
}
//listen
if(listen(server_sock_fd, BACKLOG) == -1)
{
perror("listen error");
return 1;
}
//fd_set
fd_set server_fd_set;
int max_fd = -1;
struct timeval tv; //超时时间设置
while(1)
{
tv.tv_sec = 20;
tv.tv_usec = 0;
FD_ZERO(&server_fd_set);
FD_SET(STDIN_FILENO, &server_fd_set);
if(max_fd <STDIN_FILENO)
{
max_fd = STDIN_FILENO;
}
//printf("STDIN_FILENO=%d\n", STDIN_FILENO);
//服务器端socket
FD_SET(server_sock_fd, &server_fd_set);
// printf("server_sock_fd=%d\n", server_sock_fd);
if(max_fd < server_sock_fd)
{
max_fd = server_sock_fd;
}
//客户端连接
for(int i =0; i < CONCURRENT_MAX; i++)
{
//printf("client_fds[%d]=%d\n", i, client_fds[i]);
if(client_fds[i] != 0)
{
FD_SET(client_fds[i], &server_fd_set);
if(max_fd < client_fds[i])
{
max_fd = client_fds[i];
}
}
}
int ret = select(max_fd + 1, &server_fd_set, NULL, NULL, &tv);
if(ret < 0)
{
perror("select 出错\n");
continue;
}
else if(ret == 0)
{
printf("select 超时\n");
continue;
}
else
{
//ret 为未状态发生变化的文件描述符的个数
if(FD_ISSET(STDIN_FILENO, &server_fd_set))
{
printf("发送消息:\n");
bzero(input_msg, BUFFER_SIZE);
fgets(input_msg, BUFFER_SIZE, stdin);
//输入“.quit"则退出服务器
if(strcmp(input_msg, QUIT_CMD) == 0)
{
exit(0);
}
for(int i = 0; i < CONCURRENT_MAX; i++)
{
if(client_fds[i] != 0)
{
printf("client_fds[%d]=%d\n", i, client_fds[i]);
send(client_fds[i], input_msg, BUFFER_SIZE, 0);
}
}
}
if(FD_ISSET(server_sock_fd, &server_fd_set))
{
//有新的连接请求
struct sockaddr_in client_address;
socklen_t address_len;
int client_sock_fd = accept(server_sock_fd, (struct sockaddr *)&client_address, &address_len);
printf("new connection client_sock_fd = %d\n", client_sock_fd);
if(client_sock_fd > 0)
{
int index = -1;
for(int i = 0; i < CONCURRENT_MAX; i++)
{
if(client_fds[i] == 0)
{
index = i;
client_fds[i] = client_sock_fd;
break;
}
}
if(index >= 0)
{
printf("新客户端(%d)加入成功 %s:%d\n", index, inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
}
else
{
bzero(input_msg, BUFFER_SIZE);
strcpy(input_msg, "服务器加入的客户端数达到最大值,无法加入!\n");
send(client_sock_fd, input_msg, BUFFER_SIZE, 0);
printf("客户端连接数达到最大值,新客户端加入失败 %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
}
}
}
for(int i =0; i < CONCURRENT_MAX; i++)
{
if(client_fds[i] !=0)
{
if(FD_ISSET(client_fds[i], &server_fd_set))
{
//处理某个客户端过来的消息
bzero(recv_msg, BUFFER_SIZE);
long byte_num = recv(client_fds[i], recv_msg, BUFFER_SIZE, 0);
if (byte_num > 0)
{
if(byte_num > BUFFER_SIZE)
{
byte_num = BUFFER_SIZE;
}
//recv_msg[byte_num] = '\0';
printf("客户端(%d):%s", i, recv_msg);
/*转发数据给其他的客户端*/
for(int i = 0; i < CONCURRENT_MAX; i++)
{
if(client_fds[i] != 0)
{
send(client_fds[i], recv_msg, sizeof(recv_msg), 0);
}
}
/*结束转发内容*/
}
else if(byte_num < 0)
{
printf("从客户端(%d)接受消息出错.\n", i);
}
else
{
FD_CLR(client_fds[i], &server_fd_set);
client_fds[i] = 0;
printf("客户端(%d)退出了\n", i);
}
}
}
}
}
}
return 0;
}

总结

socket通信里面还有很多东西值得去研读,想想以前参加比赛的时候因为网络通信困扰了很长时间,最后还是通过别人的服务器进行操作的.现在这几天就把app到服务器在到终端打通了,虽然只是一个很简单的demo,但是别的东西无非在这基础上进行优化改进的.
继续加油,走在驱动开发的小白.