c語言socket雙向通信+一服務端對多客戶端通信


任務

在完成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,但是別的東西無非在這基礎上進行優化改進的.
繼續加油,走在驅動開發的小白.


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com