From a871fc1882a4db57ef3d9a0c7f963f255cdd6794 Mon Sep 17 00:00:00 2001 From: xia-chu <771730766@qq.com> Date: Mon, 23 Oct 2023 20:58:12 +0800 Subject: [PATCH] =?UTF-8?q?websocket=E6=9C=8D=E5=8A=A1=E5=99=A8=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=9C=A8=E5=88=9B=E5=BB=BA=E5=99=A8=E4=B8=AD=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E6=B6=88=E6=81=AF=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 通过该修改可以更灵活的指定同端口下不同websocket服务的消息类型 --- src/Http/WebSocketSession.h | 9 +++++---- tests/test_wsServer.cpp | 4 +++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Http/WebSocketSession.h b/src/Http/WebSocketSession.h index 96021c4d..8978330c 100644 --- a/src/Http/WebSocketSession.h +++ b/src/Http/WebSocketSession.h @@ -69,7 +69,7 @@ template class SessionCreator { public: //返回的Session必须派生于SendInterceptor,可以返回null - toolkit::Session::Ptr operator()(const mediakit::Parser &header, const mediakit::HttpSession &parent, const toolkit::Socket::Ptr &pSock){ + toolkit::Session::Ptr operator()(const mediakit::Parser &header, const mediakit::HttpSession &parent, const toolkit::Socket::Ptr &pSock, mediakit::WebSocketHeader::Type &data_type){ return std::make_shared >(header,parent,pSock); } }; @@ -128,7 +128,8 @@ protected: */ bool onWebSocketConnect(const mediakit::Parser &header) override{ //创建websocket session类 - _session = _creator(header, *this, HttpSessionType::getSock()); + auto data_type = DataType; + _session = _creator(header, *this, HttpSessionType::getSock(), data_type); if (!_session) { // 此url不允许创建websocket连接 return false; @@ -140,13 +141,13 @@ protected: //此处截取数据并进行websocket协议打包 std::weak_ptr weakSelf = std::static_pointer_cast(HttpSessionType::shared_from_this()); - std::dynamic_pointer_cast(_session)->setOnBeforeSendCB([weakSelf](const toolkit::Buffer::Ptr &buf) { + std::dynamic_pointer_cast(_session)->setOnBeforeSendCB([weakSelf, data_type](const toolkit::Buffer::Ptr &buf) { auto strongSelf = weakSelf.lock(); if (strongSelf) { mediakit::WebSocketHeader header; header._fin = true; header._reserved = 0; - header._opcode = DataType; + header._opcode = data_type; header._mask_flag = false; strongSelf->HttpSessionType::encode(header, buf); } diff --git a/tests/test_wsServer.cpp b/tests/test_wsServer.cpp index bd46787a..f839d352 100644 --- a/tests/test_wsServer.cpp +++ b/tests/test_wsServer.cpp @@ -81,9 +81,11 @@ public: */ struct EchoSessionCreator { //返回的Session必须派生于SendInterceptor,可以返回null(拒绝连接) - Session::Ptr operator()(const Parser &header, const HttpSession &parent, const Socket::Ptr &pSock) { + Session::Ptr operator()(const Parser &header, const HttpSession &parent, const Socket::Ptr &pSock, mediakit::WebSocketHeader::Type &type) { // return nullptr; if (header.url() == "/") { + // 可以指定传输方式 + // type = mediakit::WebSocketHeader::BINARY; return std::make_shared >(header, parent, pSock); } return std::make_shared >(header, parent, pSock);