Git Product home page Git Product logo

sylar-yin / sylar Goto Github PK

View Code? Open in Web Editor NEW
3.7K 72.0 929.0 1.03 MB

C++高性能分布式服务器框架,webserver,websocket server,自定义tcp_server(包含日志模块,配置模块,线程模块,协程模块,协程调度模块,io协程调度模块,hook模块,socket模块,bytearray序列化,http模块,TcpServer模块,Websocket模块,Https模块等, Smtp邮件模块, MySQL, SQLite3, ORM,Redis,Zookeeper)

Home Page: http://www.sylar.top

CMake 2.10% Makefile 0.02% C++ 57.15% C 39.41% Ragel 1.25% Shell 0.07%
cpp distribution framework high-performance network fiber coroutine http-server http-client websocket-server

sylar's Introduction

视频地址

[C++高级教程]从零开始开发服务器框架(sylar)

视频教程内容:

1.日志模块

支持流式日志风格写日志和格式化风格写日志,支持日志格式自定义,日志级别,多日志分离等等功能 流式日志使用:SYLAR_LOG_INFO(g_logger) << "this is a log"; 格式化日志使用:SYLAR_LOG_FMT_INFO(g_logger, "%s", "this is a log"); 支持时间,线程id,线程名称,日志级别,日志名称,文件名,行号等内容的自由配置

2.配置模块

采用约定由于配置的**。定义即可使用。不需要单独去解析。支持变更通知功能。使用YAML文件做为配置内容。支持级别格式的数据类型,支持STL容器(vector,list,set,map等等),支持自定义类型的支持(需要实现序列化和反序列化方法)使用方式如下:

static sylar::ConfigVar<int>::ptr g_tcp_connect_timeout =
	sylar::Config::Lookup("tcp.connect.timeout", 5000, "tcp connect timeout");

定义了一个tcp连接超时参数,可以直接使用 g_tcp_connect_timeout->getValue() 获取参数的值,当配置修改重新加载,该值自动更新 上述配置格式如下:

tcp:
    connect:
            timeout: 10000

3.线程模块

线程模块,封装了pthread里面的一些常用功能,Thread,Semaphore,Mutex,RWMutex,Spinlock等对象,可以方便开发中对线程日常使用 为什么不适用c++11里面的thread 本框架是使用C++11开发,不使用thread,是因为thread其实也是基于pthread实现的。并且C++11里面没有提供读写互斥量,RWMutex,Spinlock等,在高并发场景,这些对象是经常需要用到的。所以选择了自己封装pthread

4.协程模块

协程:用户态的线程,相当于线程中的线程,更轻量级。后续配置socket hook,可以把复杂的异步调用,封装成同步操作。降低业务逻辑的编写复杂度。 目前该协程是基于ucontext_t来实现的,后续将支持采用boost.context里面的fcontext_t的方式实现

5.协程调度模块

协程调度器,管理协程的调度,内部实现为一个线程池,支持协程在多线程中切换,也可以指定协程在固定的线程中执行。是一个N-M的协程调度模型,N个线程,M个协程。重复利用每一个线程。

6.IO协程调度模块

继承与协程调度器,封装了epoll(Linux),并支持定时器功能(使用epoll实现定时器,精度毫秒级),支持Socket读写时间的添加,删除,取消功能。支持一次性定时器,循环定时器,条件定时器等功能

7.Hook模块

hook系统底层和socket相关的API,socket io相关的API,以及sleep系列的API。hook的开启控制是线程粒度的。可以自由选择。通过hook模块,可以使一些不具异步功能的API,展现出异步的性能。如(mysql)

8.Socket模块

封装了Socket类,提供所有socket API功能,统一封装了地址类,将IPv4,IPv6,Unix地址统一起来。并且提供域名,IP解析功能。

9.ByteArray序列化模块

ByteArray二进制序列化模块,提供对二进制数据的常用操作。读写入基础类型int8_t,int16_t,int32_t,int64_t等,支持Varint,std::string的读写支持,支持字节序转化,支持序列化到文件,以及从文件反序列化等功能

10.TcpServer模块

基于Socket类,封装了一个通用的TcpServer的服务器类,提供简单的API,使用便捷,可以快速绑定一个或多个地址,启动服务,监听端口,accept连接,处理socket连接等功能。具体业务功能更的服务器实现,只需要继承该类就可以快速实现

11.Stream模块

封装流式的统一接口。将文件,socket封装成统一的接口。使用的时候,采用统一的风格操作。基于统一的风格,可以提供更灵活的扩展。目前实现了SocketStream

12.HTTP模块

采用Ragel(有限状态机,性能媲美汇编),实现了HTTP/1.1的简单协议实现和uri的解析。基于SocketStream实现了HttpConnection(HTTP的客户端)和HttpSession(HTTP服务器端的链接)。基于TcpServer实现了HttpServer。提供了完整的HTTP的客户端API请求功能,HTTP基础API服务器功能

13.Servlet模块

仿照java的servlet,实现了一套Servlet接口,实现了ServletDispatch,FunctionServlet。NotFoundServlet。支持uri的精准匹配,模糊匹配等功能。和HTTP模块,一起提供HTTP服务器功能

14.其他相关

联系方式: QQ:564628276 邮箱:[email protected] 微信:sylar-yin QQ群:8151915(sylar技术群) 个人主页:www.sylar.top github:https://github.com/sylar-yin/sylar

sylar's People

Contributors

sylar-yin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sylar's Issues

关于ZooKeeper C库的错误

usr/bin/c++ -DDBUG_OFF -Dsylar_EXPORTS -D__FILE__="sylar/zk_client.cc" -I/home/ly/pointer/sylar-master/. -I/apps/sylar/include -I/usr/include/mysql -rdynamic -O3 -fPIC -ggdb -std=c++11 -Wall -Wno-deprecated -Werror -Wno-unused-function -Wno-builtin-macro-redefined -Wno-deprecated-declarations -fPIC -o CMakeFiles/sylar.dir/sylar/zk_client.cc.o -c /home/ly/pointer/sylar-master/sylar/zk_client.cc
/home/ly/pointer/sylar-master/sylar/zk_client.cc:21:44: error: ‘ZOO_CONTAINER’ was not declared in this scope; did you mean ‘CONTAINER’?
21 | const int ZKClient::FlagsType::CONTAINER = ZOO_CONTAINER;
| ^~~~~~~~~~~~~
| CONTAINER
/home/ly/pointer/sylar-master/sylar/zk_client.cc:28:43: error: ‘ZOO_READONLY_STATE’ was not declared in this scope
28 | const int ZKClient::StateType::READONLY = ZOO_READONLY_STATE;
| ^~~~~~~~~~~~~~~~~~
/home/ly/pointer/sylar-master/sylar/zk_client.cc:29:47: error: ‘ZOO_NOTCONNECTED_STATE’ was not declared in this scope; did you mean ‘ZOO_CONNECTED_STATE’?
29 | const int ZKClient::StateType::NOTCONNECTED = ZOO_NOTCONNECTED_STATE;
| ^~~~~~~~~~~~~~~~~~~~~~
| ZOO_CONNECTED_STATE
/home/ly/pointer/sylar-master/sylar/zk_client.cc: In member function ‘bool sylar::ZKClient::reconnect()’:
/home/ly/pointer/sylar-master/sylar/zk_client.cc:52:16: error: ‘zookeeper_init2’ was not declared in this scope; did you mean ‘zookeeper_init’?
52 | m_handle = zookeeper_init2(m_hosts.c_str(), &ZKClient::OnWatcher, m_recvTimeout, nullptr, this, 0, m_logCb);
| ^~~~~~~~~~~~~~~
| zookeeper_init
/home/ly/pointer/sylar-master/sylar/zk_client.cc: In member function ‘bool sylar::ZKClient::init(const string&, int, sylar::ZKClient::watcher_callback, sylar::ZKClient::log_callback)’:
/home/ly/pointer/sylar-master/sylar/zk_client.cc:67:16: error: ‘zookeeper_init2’ was not declared in this scope; did you mean ‘zookeeper_init’?
67 | m_handle = zookeeper_init2(hosts.c_str(), &ZKClient::OnWatcher, m_recvTimeout, nullptr, this, 0, lcb);
| ^~~~~~~~~~~~~~~
| zookeeper_init
/home/ly/pointer/sylar-master/sylar/zk_client.cc: In member function ‘int32_t sylar::ZKClient::setServers(const string&)’:
/home/ly/pointer/sylar-master/sylar/zk_client.cc:72:15: error: ‘zoo_set_servers’ was not declared in this scope
72 | auto rt = zoo_set_servers(m_handle, hosts.c_str());
| ^~~~~~~~~~~~~~~
/home/ly/pointer/sylar-master/sylar/zk_client.cc: In member function ‘int32_t sylar::ZKClient::getConfig(std::string&, bool, Stat*)’:
/home/ly/pointer/sylar-master/sylar/zk_client.cc:103:16: error: ‘ZOO_CONFIG_NODE’ was not declared in this scope
103 | return get(ZOO_CONFIG_NODE, val, watch, stat);
| ^~~~~~~~~~~~~~~
/home/ly/pointer/sylar-master/sylar/zk_client.cc: In member function ‘std::string sylar::ZKClient::getCurrentServer()’:
/home/ly/pointer/sylar-master/sylar/zk_client.cc:137:15: error: ‘zoo_get_current_server’ was not declared in this scope; did you mean ‘getCurrentServer’?
137 | auto rt = zoo_get_current_server(m_handle);
| ^~~~~~~~~~~~~~~~~~~~~~
| getCurrentServer
make[2]: *** [CMakeFiles/sylar.dir/build.make:865:CMakeFiles/sylar.dir/sylar/zk_client.cc.o] 错误 1
make[2]: 离开目录“/home/ly/pointer/sylar-master/build”
make[1]: *** [CMakeFiles/Makefile2:248:CMakeFiles/sylar.dir/all] 错误 2
make[1]: 离开目录“/home/ly/pointer/sylar-master/build”
make: *** [Makefile:87:all] 错误 2

@sylar-yin 作者大大这个问题怎么解决呀?
有大佬解释一下这个是如何解决的吗

关于bytearray的设计问题

作者大大,我看bytearray中无论write还是read,m_position指针都会变化,为什么不将m_position分成读写两个指针,会不会更加方便一点?

httpserver的长连接有bug

httpserver的handleclient函数在处理长连接时会不停循环,我在压力测试时,服务器开启后首次测试时,长连接不会出现问题,但是在不关闭服务器的情况下,第二次压力测试时,服务器仅能处理第一个长连接,它会在第一个长连接那里不停循环,我在判断长连接语句后边重新把handleclient函数放入调度器里,解决了这个问题,不知道为什么第一次压力测试时可以正常处理长连接,后边就不行了

日志的format格式输入在展开的代码中,最后一个参数如果 __VA_ARGS__ 被解析为空,会导致编译错误,加##解决

源代码

/**
 * @brief 使用格式化方式将日志级别level的日志写入到logger
 */
#define SYLAR_LOG_FMT_LEVEL(logger, level, fmt, ...) \
    if(logger->getLevel() <= level) \
        sylar::LogEventWrap(sylar::LogEvent::ptr(new sylar::LogEvent(logger, level, \
                        __FILE__, __LINE__, 0, sylar::GetThreadId(),\
                sylar::GetFiberId(), time(0), sylar::Thread::GetName()))).getEvent()->format(fmt, __VA_ARGS__)

/**
 * @brief 使用格式化方式将日志级别debug的日志写入到logger
 */
#define SYLAR_LOG_FMT_DEBUG(logger, fmt, ...) SYLAR_LOG_FMT_LEVEL(logger, sylar::LogLevel::DEBUG, fmt, __VA_ARGS__)

...
...

修改后

/**
 * @brief 使用格式化方式将日志级别level的日志写入到logger
 */
#define SYLAR_LOG_FMT_LEVEL(logger, level, fmt, ...) \
    if(logger->getLevel() <= level) \
        sylar::LogEventWrap(sylar::LogEvent::ptr(new sylar::LogEvent(logger, level, \
                        __FILE__, __LINE__, 0, sylar::GetThreadId(),\
                sylar::GetFiberId(), time(0), sylar::Thread::GetName()))).getEvent()->format(fmt, ##__VA_ARGS__)

/**
 * @brief 使用格式化方式将日志级别debug的日志写入到logger
 */
#define SYLAR_LOG_FMT_DEBUG(logger, fmt, ...) SYLAR_LOG_FMT_LEVEL(logger, sylar::LogLevel::DEBUG, fmt, ##__VA_ARGS__)

...
...

protobuf

/root/xzy/sylar-master/sylar/ns/ns_protobuf.pb.h:12:2: error: #error This file was generated by a newer version of protoc which is
#error This file was generated by a newer version of protoc which is
^
/root/xzy/sylar-master/sylar/ns/ns_protobuf.pb.h:13:2: error: #error incompatible with your Protocol Buffer headers. Please update
#error incompatible with your Protocol Buffer headers. Please update
^
/root/xzy/sylar-master/sylar/ns/ns_protobuf.pb.h:14:2: error: #error your headers.
#error your headers.
^
In file included from /root/xzy/sylar-master/sylar/ns/ns_protocol.h:10:0,
from /root/xzy/sylar-master/sylar/ns/name_server_module.h:5,
from /root/xzy/sylar-master/sylar/ns/name_server_module.cc:1:
/root/xzy/sylar-master/sylar/ns/ns_protobuf.pb.h:47:16: error: ‘AuxiliaryParseTableField’ in namespace ‘google::protobuf::internal’ does not name a type
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
^
/root/xzy/sylar-master/sylar/ns/ns_protobuf.pb.h:95:27: error: expected initializer before ‘:’ token
class Node PROTOBUF_FINAL :
^
In file included from /root/xzy/sylar-master/sylar/ns/ns_protocol.h:10:0,
from /root/xzy/sylar-master/sylar/ns/name_server_module.h:5,
from /root/xzy/sylar-master/sylar/ns/name_server_module.cc:1:
/root/xzy/sylar-master/sylar/ns/ns_protobuf.pb.h:1307:30: error: expected ‘}’ before end of line
#pragma GCC diagnostic push

日志库对%%解析有BUG

解析%%%p%%会失败.
应该在判断%%成功后, 使++i

if ((i + 1) < pattern_.size())
{
    if (pattern_[i + 1] == '%')
    {
            nstr.append(1, '%');
            ++i;
            continue;
    }
}

Fiber的reset方法问题

Fiber的构造函数中使用user_caller判断是否使用调度器
if(!use_caller) { makecontext(&m_ctx, &Fiber::MainFunc, 0); } else { makecontext(&m_ctx, &Fiber::CallerMainFunc, 0); }
但是在reset中直接调用了Mainfunc
makecontext(&m_ctx, &Fiber::MainFunc, 0);
reset方法中是否也需要加一个类似的判断?

可能的bug

发现两个可能的bug,都是与多线程安全有关

  1. IOManager 模块中,定时器的调度可能使其他线程误以为没有任务而stopping终止。
  2. 对于协程调度中,在添加事件监听后,YieldHold协程之前,如果由于事件触发,导致该协程被加入调度,并被其他线程调度了,此时同一协程被两个线程同时调度而发生异常。

编译该库时失败

您好,我已经按照您的安装环境的要求进行了环境的配置,并且在配置环境过程中都成功了,十分顺利,但在下载该库进行编译,make时,报了如下的错误:
-- The C compiler identification is GNU 4.8.5
-- The CXX compiler identification is GNU 4.8.5
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Deprecation Warning at thirdpart/yaml-cpp/CMakeLists.txt:9 (cmake_policy):
The OLD behavior for policy CMP0012 will be removed from a future version
of CMake.

The cmake-policies(7) manual explains that the OLD behaviors of all
policies are deprecated and that a policy should be set to OLD only under
specific short-term circumstances. Projects should be ported to the NEW
behavior and not rely on setting a policy to OLD.

CMake Deprecation Warning at thirdpart/yaml-cpp/CMakeLists.txt:13 (cmake_policy):
The OLD behavior for policy CMP0015 will be removed from a future version
of CMake.

The cmake-policies(7) manual explains that the OLD behaviors of all
policies are deprecated and that a policy should be set to OLD only under
specific short-term circumstances. Projects should be ported to the NEW
behavior and not rely on setting a policy to OLD.

-- Performing Test FLAG_WEXTRA
-- Performing Test FLAG_WEXTRA - Success
-- JsonCpp Version: 1.8.4
-- Looking for C++ include clocale
-- Looking for C++ include clocale - found
-- Looking for localeconv
-- Looking for localeconv - found
-- Looking for C++ include sys/types.h
-- Looking for C++ include sys/types.h - found
-- Looking for C++ include stdint.h
-- Looking for C++ include stdint.h - found
-- Looking for C++ include stddef.h
-- Looking for C++ include stddef.h - found
-- Check size of lconv
-- Check size of lconv - done
-- Performing Test HAVE_DECIMAL_POINT
-- Performing Test HAVE_DECIMAL_POINT - Success
-- Found PythonInterp: /usr/bin/python2 (found suitable version "2.7.5", minimum required is "2.6")
-- Boost version: 1.53.0
CMake Error at /apps/sylar/share/cmake-3.14/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
Could NOT find Protobuf (missing: Protobuf_INCLUDE_DIR)
Call Stack (most recent call first):
/apps/sylar/share/cmake-3.14/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
/apps/sylar/share/cmake-3.14/Modules/FindProtobuf.cmake:594 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
CMakeLists.txt:28 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/fight/workspace/sylar/build/CMakeFiles/CMakeOutput.log".
See also "/home/fight/workspace/sylar/build/CMakeFiles/CMakeError.log".
make: *** [xx] 错误 1

你能帮我解答一下么,我google了好久也一直没有解决,我也通过yum install 了protobuf,还是没有解决。谢谢

OpenSSL 1.1.1g Coredown

In OpenSSL 1.1.1g Coredown.

(gdb) bt
#0  0x0000000000000000 in ?? ()
#1  0x00007f0f4a931b5c in do_io<long (*)(int, void*, unsigned long), void*&, unsigned long&> (fd=3, fun=0x0, hook_fun_name=0x7f0f4a9a51c1 "read", event=1, timeout_so=20) at /root/sylar/hook.cc:81
#2  0x00007f0f4a92fe22 in read (fd=3, buf=0x7fff097d4b06, count=2) at /root/sylar/hook.cc:314
#3  0x00007f0f49cb10bd in OPENSSL_init_library () from /usr/lib64/libcrypto.so.1.1
#4  0x00007f0f4ac18d2a in call_init.part () from /lib64/ld-linux-x86-64.so.2
#5  0x00007f0f4ac18e2a in _dl_init () from /lib64/ld-linux-x86-64.so.2
#6  0x00007f0f4ac0a06a in _dl_start_user () from /lib64/ld-linux-x86-64.so.2
#7  0x0000000000000001 in ?? ()
#8  0x00007fff097d5176 in ?? ()
#9  0x0000000000000000 in ?? ()
[root@192 ~]# cat /etc/redhat-release 
CentOS Linux release 8.0.1905 (Core) 
[root@192 ~]# uname -a
Linux 192.168.1.6 4.18.0-80.el8.x86_64 #1 SMP Tue Jun 4 09:19:46 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
[root@192 ~]# openssl version
OpenSSL 1.1.1g FIPS  21 Apr 2020

So strange in openssl lib.

RockStream::request 线程安全问题

RockStream作为AsyncSocketStream的子类 实现了上层协议的收发以及解析
在request方法里

RockResult::ptr RockStream::request(RockRequest::ptr req, uint32_t timeout_ms) {                                    
        ...
        RockCtx::ptr ctx = std::make_shared<RockCtx>();                                                             
        ctx->request = req;                                                                                         
        ctx->sn = req->getSn();                                                                                     
        ctx->timeout = timeout_ms;                                                                                  
        ctx->scheduler = sylar::Scheduler::GetThis();                                                               
        ctx->fiber = sylar::Fiber::GetThis();
        addCtx(ctx); 
        uint64_t ts = sylar::GetCurrentMS();                                                                        
        ctx->timer = sylar::IOManager::GetThis()->addTimer(timeout_ms,                                              
                std::bind(&RockStream::onTimeOut, shared_from_this(), ctx));                                        
        enqueue(ctx);                                                                                               
        sylar::Fiber::YieldToHold();
        auto rt = std::make_shared<RockResult>(ctx->result, ctx->resultStr, sylar::GetCurrentMS() - ts, ctx->response, req);
        rt->server = getRemoteAddressString();                                                                      
        return rt;                           

在request方法里 在把ctx入队后 调YieldToHold等待响应
ctx入队后唤醒AsyncSocketStream的发送队列 将请求发出去 如果有响应则调doRsp

void AsyncSocketStream::Ctx::doRsp() {
    Scheduler* scd = scheduler;
    if(!sylar::Atomic::compareAndSwapBool(scheduler, scd, (Scheduler*)nullptr)) {
        return;
    }
    if(!scd || !fiber) {
        return;
    }
    if(timer) {
        timer->cancel();
        timer = nullptr;
    }

    if(timed) {
        result = TIMEOUT;
        resultStr = "timeout";
    }
    scd->schedule(&fiber);
}

doRsp里调schedule(&fiber) 返回到YeildToHold处

这里有个疑问就是 在多线程情况下
如果request里 入队后很快得到响应 快到还没来及调YeildToHold 那么就会出问题

fiber

fiber模块感觉还是有点问题,有一定概率会导致程序僵死core掉

在docker中无法正确hook

在开发环境下项目正常运行
但当想要将项目移植到docker内部时发现dl链接hook时会报错或者hook失败不会执行hook部分代码
进而导致的问题是 涉及到hook关于网络通信方面的接口无法使用
开发环境与docker内部环境一致

询问是否有解决方案,若无解决方案,建议开发者不要再docker中使用sylar的网络通信模块

address.cc文件中 IPV4address和IPV6address 中的setport方法存在问题

setport方法的函数声明为 void setPort(uint32_t v) override;
当端口号为uint16_t时,会出现调用setPort总是设置端口号为0;
比如我们想要设置端口号0x1234(人类视角)此时v在小端机器中为 0x34120000(左边是低位字节),此时程序执行步骤如下:
1, 进行byteswap 0x34120000 -> 0x00001234 (左边低位字节)
2, 将uint32_t 截断为uint16_t 0x00001234 -> 0x0000
这样设置的端口号一直是0x0000

测试代码如下:

#include "endian.h"
#include <iostream>
#include <stdint.h>
int main(){ 
    if(SYLAR_BYTE_ORDER==SYLAR_LITTLE_ENDIAN){
        std::cout<<"little endian"<<std::endl;
    }else if (SYLAR_BYTE_ORDER==SYLAR_BIG_ENDIAN){
        std::cout<<"big endian"<<std::endl;
    }


    if(BYTE_ORDER==LITTLE_ENDIAN){
        std::cout<<"little endian"<<std::endl;
    }else if (BYTE_ORDER==BIG_ENDIAN){
        std::cout<<"big endian"<<std::endl;
    }
    //set
    uint32_t port=0x1234;
    uint16_t machine=sylar::byteSwaponLittleEndian(port);
    std::cout<<std::hex<<"port:"<<port<<"   machine:"<<machine<<std::endl;

    //get
    uint16_t port_=0x3412;
    uint32_t machine_=sylar::byteSwaponLittleEndian(port_);
    std::cout<<std::hex<<"port:"<<port_<<"   machine:"<<machine_<<std::endl;
    return 0;
}

执行结果如下:
Screen Shot 2022-08-13 at 16 53 34

关于boost库

作者你好,依赖的boost库 是某些头文件?还是完整boost库?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.