1 Star 0 Fork 0

珎珎 / linux-learning

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
tcp_srv.cpp 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
root 提交于 2023-09-25 06:36 . select应用于tcp通信
#include "select.hpp"
#define CHECK_RET(v) if((v)==false){return false;}
int main()
{
TcpSocket lst_sock;
//创建套接字
CHECK_RET(lst_sock.Socket());
// 绑定地址信息
CHECK_RET(lst_sock.Bind("0.0.0.0",9000));
//开始监听
CHECK_RET(lst_sock.Listen());
//引入 select ,只针对就绪的描述符进行操作
Select s;
s.Add(lst_sock);
//获取新建连接
while(1){
std::vector<TcpSocket> array;
bool ret=s.Wait(&array,3); //进行监控就绪描述符填充到 array 数组中,3-表示超时时间
if(ret==false){
continue;
}
for(auto sock:array){ //遍历就绪描述符集合
if(sock.GetFd() == lst_sock.GetFd())
{
//描述符判等,若此时描述符等于监听套接字的描述符
//当前是监控套接字 --- 获取新建连接
TcpSocket new_sock;
bool ret=lst_sock.Accept(&new_sock);
if(ret==false){
continue;
}
s.Add(new_sock); //监控新建连接
}
//就绪描述符
//收发数据
std::string body;
ret=sock.Recv(&body);
if(ret==false){
sock.Close();
continue;
}
std::cout<<"client say: "<<body<<std::endl;
body.clear();
std::cout<<"server say: ";
fflush(stdout);
std::cin>>body;
ret=sock.Send(body);
if(ret==false){
sock.Close();
continue;
}
}
}
//关闭套接字
lst_sock.Close();
return 0;
}
C++
1
https://gitee.com/Coderxingchild/linux-learning.git
git@gitee.com:Coderxingchild/linux-learning.git
Coderxingchild
linux-learning
linux-learning
master

搜索帮助