mirror of
https://github.com/ZLMediaKit/ZLMediaKit.git
synced 2026-03-27 08:20:52 +08:00
websocket服务器支持根据url选择不同的运行逻辑
This commit is contained in:
@@ -51,6 +51,7 @@ public:
|
||||
}
|
||||
void onRecv(const Buffer::Ptr &buffer) override {
|
||||
//回显数据
|
||||
send("from EchoSession:");
|
||||
send(buffer);
|
||||
}
|
||||
void onError(const SockException &err) override{
|
||||
@@ -62,6 +63,48 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class EchoSessionWithUrl : public TcpSession {
|
||||
public:
|
||||
EchoSessionWithUrl(const Socket::Ptr &pSock) : TcpSession(pSock){
|
||||
DebugL;
|
||||
}
|
||||
virtual ~EchoSessionWithUrl(){
|
||||
DebugL;
|
||||
}
|
||||
|
||||
void attachServer(const TcpServer &server) override{
|
||||
DebugL << getIdentifier() << " " << TcpSession::getIdentifier();
|
||||
}
|
||||
void onRecv(const Buffer::Ptr &buffer) override {
|
||||
//回显数据
|
||||
send("from EchoSessionWithUrl:");
|
||||
send(buffer);
|
||||
}
|
||||
void onError(const SockException &err) override{
|
||||
WarnL << err.what();
|
||||
}
|
||||
//每隔一段时间触发,用来做超时管理
|
||||
void onManager() override{
|
||||
DebugL;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* 此对象可以根据websocket 客户端访问的url选择创建不同的对象
|
||||
*/
|
||||
struct EchoSessionCreator {
|
||||
//返回的TcpSession必须派生于SendInterceptor,可以返回null(拒绝连接)
|
||||
TcpSession::Ptr operator()(const Parser &header, const HttpSession &parent, const Socket::Ptr &pSock) {
|
||||
// return nullptr;
|
||||
if (header.Url() == "/") {
|
||||
return std::make_shared<TcpSessionTypeImp<EchoSession> >(header, parent, pSock);
|
||||
}
|
||||
return std::make_shared<TcpSessionTypeImp<EchoSessionWithUrl> >(header, parent, pSock);
|
||||
}
|
||||
};
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
//设置日志
|
||||
Logger::Instance().add(std::make_shared<ConsoleChannel>());
|
||||
@@ -71,13 +114,19 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
TcpServer::Ptr httpSrv(new TcpServer());
|
||||
//http服务器,支持websocket
|
||||
httpSrv->start<WebSocketSession<EchoSession,HttpSession>>(80);//默认80
|
||||
httpSrv->start<WebSocketSessionBase<EchoSessionCreator,HttpSession> >(80);//默认80
|
||||
|
||||
TcpServer::Ptr httpsSrv(new TcpServer());
|
||||
//https服务器,支持websocket
|
||||
httpsSrv->start<WebSocketSession<EchoSession,HttpsSession>>(443);//默认443
|
||||
httpsSrv->start<WebSocketSessionBase<EchoSessionCreator,HttpsSession> >(443);//默认443
|
||||
|
||||
TcpServer::Ptr httpSrvOld(new TcpServer());
|
||||
//兼容之前的代码(但是不支持根据url选择生成TcpSession类型)
|
||||
httpSrvOld->start<WebSocketSession<EchoSession,HttpSession> >(8080);
|
||||
|
||||
DebugL << "请打开网页:http://www.websocket-test.com/,进行测试";
|
||||
DebugL << "连接 ws://127.0.0.1/xxxx,ws://127.0.0.1/ 测试的效果将不同,支持根据url选择不同的处理逻辑";
|
||||
|
||||
DebugL << "请打开网页:http://www.websocket-test.com/,连接 ws://127.0.0.1/测试";
|
||||
|
||||
//设置退出信号处理函数
|
||||
static semaphore sem;
|
||||
|
||||
Reference in New Issue
Block a user