select函数实现tcp服务器与客户端随时收发

2023-05-16

服务器

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>


#define ERR_MSG(msg) do{\
	fprintf(stderr, "line:%d ", __LINE__);\
	perror(msg);\
}while(0)

#define PORT 6666 				//1024~49151
#define IP 	"192.168.31.226" 	//IP地址,本机IP ifconfig

int main(int argc, const char *argv[])
{
	//创建流式套接字
	int sfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}
	printf("socket create success  sfd = %d\n", sfd);

	//设置允许端口快速被重用
	int resue = 1;
	if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &resue, sizeof(resue)) < 0)
	{
		ERR_MSG("setsockopt");
		return -1;
	}

	//填充服务器的地址信息结构体
	//真实的地址信息结构体根据地址族执行,AF_INET: man 7 ip
	struct sockaddr_in sin;
	sin.sin_family 		= AF_INET; 		//必须填AF_INET;
	sin.sin_port 		= htons(PORT); 	//端口号的网络字节序,1024~49151
	sin.sin_addr.s_addr = inet_addr(IP);  	//IP地址的网络字节序,ifconfig查看

	//绑定---必须绑定
	if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
	{
		ERR_MSG("bind");
		return -1;
	}
	printf("bind success __%d__\n", __LINE__);

	//将套接字设置为被动监听状态
	if(listen(sfd, 128) < 0)
	{
		ERR_MSG("listen");
		return -1;
	}
	printf("listen success __%d__\n", __LINE__);


	fd_set readfds, tempfds; 		//设置一个读集合
	FD_ZERO(&readfds); 		//清空集合
	FD_ZERO(&tempfds); 		//清空集合


	//将需要的文件描述符填充到集合中
	FD_SET(0, &readfds);
	FD_SET(sfd, &readfds);


	int s_res = 0;
	char buf[128] = "";

	struct sockaddr_in saveCin[1024-4];
	struct sockaddr_in cin; 	//存储连接成功的客户端的地址信息
	socklen_t addrlen = sizeof(cin);

	int newfd = -1;
	ssize_t res = -1;

	int maxfd = sfd;


	while(1)
	{
		tempfds = readfds;

		//让内核去监测集合中的文件描述符是否准备就绪
		s_res = select(maxfd+1, &tempfds, NULL, NULL, NULL);
		if(s_res < 0)
		{
			ERR_MSG("select");
			return -1;
		}
		else if(0 == s_res)
		{
			printf("time out...\n");
			break;
		}
	//	printf("__%d__\n", __LINE__);
		
		//能运行到当前位置,则代表文件描述符集合中,有文件描述符准备就绪
		//需要判断是哪个文件描述符准备就绪,
		//则运行对应的处理函数,取出事件。

		//当事件产生后,集合中会只剩下触发事件的文件描述符。
		//例如:0号产生事件,则会只剩下0
		//sfd产生事件,则会只剩下sfd
		//0和sfd均产生事件,则0和sfd均存在
		//所以,下面只需要判断集合中剩下哪个文件描述符,走对应操作即可

		for(int i=0; i<=maxfd; i++) 		//maxfd是集合中最大的文件描述符,所以需要包括到maxfd
		{
			if(FD_ISSET(i, &tempfds) == 0) 		//当i所在表的文件描述符不在集合中
			{
				continue;
			}

			//能运行到当前位置,则说明i所代表的文件描述符在集合中
			//所以需要判断i所代表的文件描述符是什么,如果为0,则走fgets,如果为sfd,则走accept
			//取余走recv
			if(0 == i)
			{
			//	printf("触发键盘输入事件>>> ");
			//	fflush(stdout);
 				
				int sndfd;
				res = scanf("%d %s", &sndfd, buf);
				while(getchar()!=10);
				if(res != 2)
				{
					fprintf(stderr,"请输入正确格式:文件描述符 内容\n");
					continue;
				}
				//能运行到当前位置,则代表输入的数据格式符合要求
				if(sndfd>=1024 || sndfd<=sfd || !FD_ISSET(sndfd, &readfds))
				{
					fprintf(stderr, "sndfd=%d 没有对应的客户端\n", sndfd);
					continue;
				}
	
				if(send(sndfd , buf, sizeof(buf), 0) < 0)
				{
					ERR_MSG("send");
					return -1;
				}
				printf("send success\n");

			}
			
			else if(sfd == i)
			{
				printf("触发客户端连接事件\n");
				newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
				if(newfd < 0)
				{
					ERR_MSG("accept");
					return -1;
				}
				printf("[%s : %d] newfd=%d 客户端连接成功\n", \
						inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);

				saveCin[newfd-4] = cin;

				//将新生成的文件描述符newfd,添加到集合中
				FD_SET(newfd, &readfds);

				//更新maxfd
				maxfd = maxfd>newfd?maxfd:newfd;

			}
			else
			{
				printf("触发客户端交互事件\n");
				bzero(buf, sizeof(buf));
				//接收
				res = recv(i, buf, sizeof(buf), 0);
				if(res < 0)
				{
					ERR_MSG("recv");
				}
				else if(0 == res)
				{
					fprintf(stderr, "[%s : %d] newfd=%d 客户端下线\n", \
							inet_ntoa(saveCin[i-4].sin_addr), ntohs(saveCin[i-4].sin_port), i);
					//关闭文件描述符
					close(i);
					//将该文件描述符从集合中剔除
					FD_CLR(i, &readfds);
					//更新maxfd , 从大往小判断最大的文件描述符
					for(int j=maxfd; j>sfd; j--)
					{
						if(FD_ISSET(j, &readfds))
						{
							maxfd = j;
							break;
						}
					}
				}
				else
				{
					printf("[%s : %d] newfd=%d : %s\n", \
							inet_ntoa(saveCin[i-4].sin_addr), ntohs(saveCin[i-4].sin_port), i, buf);
					//发送 -- 将数据拼接一个 *_* 发送回去
			//		strcat(buf, "*_*");
					if(send(i, buf, sizeof(buf), 0) < 0)
					{
						ERR_MSG("send");
						return -1;
					}
					printf("send success\n");
				}

			}
		}
	}


	/*

	   while(1)
	   {
	   newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
	   if(newfd < 0)
	   {
	   ERR_MSG("accept");
	   return -1;
		}
		printf("[%s : %d] newfd=%d 客户端连接成功\n", \
				inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);

		while(1)
		{
			bzero(buf, sizeof(buf));
			//接收
			res = recv(newfd, buf, sizeof(buf), 0);
			if(res < 0)
			{
				ERR_MSG("recv");
				return -1;
			}
			else if(0 == res)
			{
				fprintf(stderr, "[%s : %d] newfd=%d 客户端下线\n", \
						inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);
				break;
			}
			printf("[%s : %d] newfd=%d : %s\n", \
					inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, buf);

		}
		close(newfd);
	}
	*/

	//关闭所有套接字文件描述符
	close(sfd);
	return 0;
}

客户端

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>                             
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#define ERR_MSG(msg) do{\
    fprintf(stderr,"line:%d",__LINE__);\
    perror(msg);\
}while(0)
#define PORT 6666      //1026~49151
#define ip "192.168.31.226"  //本机IP
int main(int argc, const char *argv[])
{
    //创建流式套接字
    int cfd=socket(AF_INET,SOCK_STREAM,0);
    if(cfd<0)
    {
        ERR_MSG("socket");
        return -1;
    }
    printf("socket create success cfd=%d\n",cfd);
    //填充客户端的地址信息结构体
    //真是的地址信息结构体根据地址族执行,AF_INET:man 7 ip
    struct sockaddr_in sin;
    sin.sin_family =AF_INET;//必须填AF_INET
    sin.sin_port = htons(PORT);//端口号的网络字节序 1024~49151
    sin.sin_addr.s_addr = inet_addr(ip);         //IP地址的网络字节序,ifconfig查看

	fd_set readfds,tempfds;//设置一个读集合
	FD_ZERO(&readfds);//清空集合
	FD_ZERO(&tempfds);//清空集合

	//将需要的文件描述符填充到集合中
	FD_SET(0,&readfds);
	FD_SET(cfd,&readfds);

   	//连接服务器
	if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))<0)
	{
		ERR_MSG("connect");
		return -1;
	}
	printf("connect sunccess\n");
	int s_res=0;
	int maxfd=cfd;
    char buf[128]="";
    ssize_t res=-1;

	int i=-1;
	while(1)
	{
		tempfds=readfds;
		s_res=select(maxfd+1,&tempfds,NULL,NULL,NULL);
		if(s_res<0)
		{
			ERR_MSG("select");
			return -1;
		}
		else if(0==s_res)
		{
			printf("time out...\n");
			return -1;
		}

		for(i=0;i<=maxfd;i++)
		{
			if(FD_ISSET(i,&tempfds)==0)
			{
				continue;
			}
			if(0==i)
			{
				bzero(buf,sizeof(buf));

				//发送 	
				fgets(buf,sizeof(buf),stdin);
				buf[strlen(buf)-1]='\0';
				if(send(cfd,buf, sizeof(buf),0)<0)
				{
					ERR_MSG("send");
					return -1;
				}
				printf("send sunccess\n");
			}
			else if(cfd==i) 
			{
				//接受       
				bzero(buf,sizeof(buf));

				res=recv(cfd,buf,sizeof(buf),0);
				if(res<0)
				{
					ERR_MSG("recv");
					return -1;
				}
				else if(0==res)
				{
					fprintf(stderr,"服务器关闭\n");
					break;

				}
				printf(": %s\n" ,buf);
			}
		}
	}

	//关闭所有套接字文件描述符
	close(cfd);

	return 0;
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

select函数实现tcp服务器与客户端随时收发 的相关文章

  • esp32 tcp socket客户端收发代码

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • esp32 event loop handle 代码

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • esp32 ble gatt server创建多个Characteristic

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • freertos入门之创建Task

    基于esp32平台 span class token macro property span class token directive hash span span class token directive keyword includ
  • freertos入门之queue

    基于esp32 平台 参考 xff1a https www freertos org fr content src uploads 2018 07 161204 Mastering the FreeRTOS Real Time Kernel
  • freertos入门之binary semaphore

    基于esp32 平台 参考 xff1a https www freertos org fr content src uploads 2018 07 161204 Mastering the FreeRTOS Real Time Kernel
  • freertos入门之EventGroup

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • freertos入门之Timer

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • freertos入门之StreamBuffer

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • 设置cpp-httplib 服务器模式模式下的线程池大小 以及如何增加默认处理函数 以便能够实现http请求转发

    先说说默认的创建的线程池数量 原因是某天调试在gdb调试下 一启动程序发现 开启了好多线程 如下图 因为我们程序 没几个线程 数了下 居然有60多个线程 不需要那么多 所以看下 httplib的源码 构造函数的时候 设置了最大线程池数量 看
  • freertos入门之StreamBuffer

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • arduino-esp32 入门之wifi连接热点

    参考 xff1a https github com espressif arduino esp32 blob master libraries WiFi examples WiFiClient WiFiClient ino span cla
  • esp32-arduino入门之点亮led

    参考 xff1a https learncplusplus org how to program arduino with c span class token macro property span class token directi
  • stm32 学习资料汇总

    外设库以及example xff1a Google 搜索 STM32 Standard Peripheral Libraries
  • HttpClient学习研究---第四章:HTTP authenticationHTTP身份验证

    第四章 HTTP authentication HTTP身份验证 HttpClient provides full support for authentication schemes defined by the HTTP standar
  • Linux系统下常用的3个网络测试工具!

    在Linux系统中 xff0c 有很多用于管理和监测网络连接的命令 xff0c 其中ping traceroute和nslookup是比较常用的网络命令 xff0c 可以用来测试网络 诊断网络故障等等 xff0c 以下是详细的内容 xff1
  • TCP.02.SELECT模型

    文章目录 SELECT模型简介SELECT模型流程SELECT原理SELECT代码实现fd set 数组及基本操作SELECT函数参数2 xff08 重点 xff09 参数3参数4 关闭所有SOCKET句柄处理控制台窗口关闭事件整体代码思考
  • Node.js http 模块详解:request 对象

    前言 前文介绍了 http 模块的基本用法 xff0c 主要就是调用 createServer 和 listen 方法来创建和启动服务 要处理具体的 HTTP 请求 xff0c 就要在 createServer 方法中写点什么 本文来介绍处
  • 如何确认串口波特率

    文章目录 1 盲扫一遍2 示波器测量1bit时间3 逻辑分析仪确认 背景 xff1a 手上有一个模块使用串口通信但是不知道其波特率 xff0c 如何确认它的波特率呢 xff1f 1 盲扫一遍 波特率有常用的配置9600 115200 230
  • curl命令常用参数

    curl命令常用参数 curl简介常用方法将远程文件下载到本地 o并指定名称指定请求方式 X显示响应结果 v携带用户名 密码 u携带请求头 H查看服务端响应头 i只显示http response的头信息 I自动跳转 L模拟dns解析 res

随机推荐

  • 学习ZLmediaKit流媒体服务器时候遇到的问题

    照zlmediakit的源码 自己复制了一份 然后有的地方编译不过修改了部分 测试的时候发现有两个问题 第一是 ffmpeg的ffplay 能播放 vlc不能播放 第二个问题是directProxy设置为0的时候 推流的时候 然后用ffpl
  • 如何在C/C++中使用pi (π) 值

    在math h有一个宏定义M PI if defined USE MATH DEFINES amp amp defined MATH DEFINES DEFINED define MATH DEFINES DEFINED Definitio
  • 关于#include<bits/stdc++.h>

    偶然发现 span class hljs preprocessor include lt bits stdc 43 43 h gt span 包括了C 43 43 几乎所有的头文件 xff0c 感觉以后可以返璞归真了 回顾自己不长的竞赛历程
  • 单片机STM32直连电调控制航模涵道电机的方法总结

    单片机STM32直连电调控制航模涵道电机的方法总结 文章目录 单片机STM32直连电调控制航模涵道电机的方法总结前言一 硬件情况二 涵道电机两种常见的驱动方式1 有线控制方式2 无线控制方案 解决方案 前言 由于项目需要 xff0c 我需要
  • PX4之常用函数解读

    PX4Firmware 经常有人将Pixhawk PX4 APM还有ArduPilot弄混 这里首先还是简要说明一下 xff1a Pixhawk是飞控硬件平台 xff0c PX4和ArduPilot都是开源的可以烧写到Pixhawk飞控中的
  • PX4项目学习::(七)飞控栈:commander

    PX4的飞行控制程序通过模块来实现 xff0c 与飞控相关的模块主要有commander xff0c navigator xff0c pos control xff0c att control这几个 xff0c 分别可以在src modul
  • PX4项目学习::(五)模块代码启动流程

    54条消息 PX4 模块代码启动流程 zhao23333的博客 CSDN博客
  • TX2指南(一)TX2接显示器的问题

    TX2开发板一定要适配HDMI显示器 xff0c 使用转接头在VGA显示器会显示 input signal out of range xff01 所以目前来看手上的这套TX2只能适配HDMI显示器 xff0c 目前还不清楚是不是所有的TX2
  • 推荐定位信息(GPRMC)

    推荐定位信息 GPRMC GPRMC lt 1 gt lt 2 gt lt 3 gt lt 4 gt lt 5 gt lt 6 gt lt 7 gt lt 8 gt lt 9 gt lt 10 gt lt 11 gt lt 12 gt hh
  • linux中使用shell命令打开指定文件夹(Nautilus@GNOME)

    在GNOME中是Nautilus 鹦鹉螺 xff0c 而KDE中是Konqueror nautilus 图形化桌面包括了一个叫做 Nautilus 的文件管理器 它给你提供了系统和个人文件的图形化显示 然而 xff0c Nautilus 不
  • 在ubuntu20.4下安装ardupilot 4.3.6

    这次重新安装真的是遇到了好多坑啊 xff01 从github上靠过来按照之前的那篇文章流程做完之后 xff0c 还会有一些别的问题 首先是module里面的包都没有拷过来 xff0c 所以需要用git add将文件都添加过来 之后进行编译时
  • Visual Studio 2022 搭建GLFW OpenGL开发环境

    最近工作需要 需要写一个全景的视频播放器 网上搜了下大概解决方案是 ffmpeg 43 opengl b站有很多视频 按照视频 搭建了OpenGL的开发环境 先去GLFW的网站下载 windows平台的库文件 为什么使用GLFW 因为GLF
  • Pixhawk原生固件PX4之自定义MAVLink消息

    欢迎交流 个人 Gitter 交流平台 xff0c 点击直达 xff1a 本着想在PX4基础上加点什么东西的我又开始折腾了 xff0c 先尝试用串口加传感器通过QGC查看 xff0c 要是能在原固件上加点内容就棒哉了 先立Flag 自定义u
  • Pixhawk原生固件PX4之MAVLink协议解析

    欢迎交流 个人 Gitter 交流平台 xff0c 点击直达 xff1a PX4 对Mavlink 协议提供了良好的原生支持 该协议既可以用于地面站 Ground ControlStation GCS 对无人机 UAV 的控制 xff0c
  • GPS和RTK的基本知识

    RTK的基本原理介绍 xff0c RTK一般由基站 移动站以及数据链路组成 下文摘自天宝 Trimble 官网 原文链接 xff1a http www trimble com OEM ReceiverHelp V4 44 en What i
  • freeRTOS系统栈与任务栈

    中断过来之后 xff0c 由任务栈切换到main stack xff08 系统栈 xff09 任务栈保存 系统栈的地址范围为0xfede8000 4K xff0c 向下生长 xff0c 所以按照ld的定义 xff0c 0xfede9000
  • ROS下上位机和stm32单片机通信

    1 需要实例化串口节点建立监听者listener和发布之publisher 2 上位机通过游戏手柄发布自定义消息类型control int64 mode 手柄模式切换 int64 lidar 雷达数据 int64 gamePad x 控制前
  • 奇偶校验码

    偶校验为例 xff1a 例图中 xff0c 下划线为校验位 xff0c 其余为信息位 检错步骤如下 xff1a 1 根据信息位算出校验位 xff08 通过异或运算 xff1a 相同为0 xff0c 不同为1 xff09 xff1a 得出校验
  • C++中#define和const的区别

    一 define是预处理指令 xff08 pre processor directive xff09 而const是关键字 define用于给一些值定义名称 字符串 xff0c 这样定义的字符串在C C 43 43 中称为宏定义 xff0c
  • select函数实现tcp服务器与客户端随时收发

    服务器 include lt stdio h gt include lt sys types h gt include lt sys socket h gt include lt arpa inet h gt include lt neti