webcat——基于netty的http和websocket框架

代码地址如下:
http://www.demodashi.com/demo/12687.html

Webcat是一个基于netty的简单、高性能服务端框架,目前提供http和websocket两种协议的快速开发模式。webcat采用spring进行对象管理,因此工程需要依赖spring框架,Github地址

下载源代码后,可以直接运行WebcatServerTest启动http和websocket服务,然后通过pytest文件夹中的两个python脚本对服务进行测试。

HTTP Server 使用

在spring的配置中,加上对webcat的package扫描:

<context:component-scan base-package="com.lchml.webcat"/>

设置端口并启动:

public static void main(String[] args) throws WebcatStartException {
    HttpServer httpServer = context.getBean(WebcatHttpServer.class);
    httpServer.setPort(8080);
    httpServer.start();
}

添加自己的controller:

<context:component-scan base-package="com.lchml.test"/>
@HttpController(path = "/test")
public class TestController {

    @HttpRequestMapping(path = "/hello", consumes = {"text/plain"})
    public String testHello() {
        return "hello webcat";
    }

    @HttpRequestMapping(path = "/bodytest", method = {ReqMethod.POST})
    public String testBody(@ReqBody String body) {
        return "hello webcat " + body;
    }

    @HttpRequestMapping(path = "/redirect", method = {ReqMethod.GET})
    public void testRedirect(FullHttpResponse response) {
        ResponseUtil.redirect(response, "http://lchml.com");
    }
}
  • logEnable,默认会打开所有websocket请求的日志。
  • logResponse,默认日志中不会输入response内容。
  • defaultProduce,默认返回content-type为application/json;charset=utf-8。
<bean class="com.lchml.webcat.config.WebcatHttpConf" id="webcatConf">
    <property name="logEnable" value="true"/>
    <property name="logResponse" value="true"/>
    <property name="defaultProduce" value="application/json;charset=utf-8"/>
</bean>

Websocket Server 使用

在spring的配置中,加上对webcat的package扫描:

<context:component-scan base-package="com.lchml.webcat"/>

设置端口,设置连接初始化和断开的监听回调并启动:

public static void main(String[] args) throws WebcatStartException {
    WebcatWsServer wsServer = context.getBean(WebcatWsServer.class);
    wsServer.setPort(8081);
    wsServer.setChannelConnectListener(new ChannelConnectListener() {
        @Override public void connect(ChannelInfo channelInfo) {
            channelInfo.addAttr("connectTime", System.currentTimeMillis());
            System.out.println(channelInfo.getClientIp() + " connect");
        }
    });
    wsServer.setChannelDisconnectListener(new ChannelDisconnectListener() {
        @Override public void disconnect(ChannelInfo channelInfo) {
            System.out.println(channelInfo.getClientIp() + " disconnect");
        }
    });

    wsServer.start();
}

添加自己的controller:

<context:component-scan base-package="com.lchml.test"/>
@WsController(path = "/test")
public class TestWsController {

    @WsRequestMapping(path = "/hello")
    public Object testHello(String name, WsContext ctx) {
        return "hello webcat " + name + " from " + ctx.getCi().getClientIp();
    }
}
  • heartbeat,默认心跳为15s,超过15s没有收到客户端心跳则视为连接断开。
  • useProxy,默认没有使用代理,则直接使用RemoteAddress作为客户端ip,如果设置为true,会从路由信息中获取真实客户端ip地址。
  • wsPath,默认path为/webcat,可以自行修改。
  • logEnable,默认会打开所有websocket请求的日志。
  • logResponse,默认日志中不会输入response内容。
<bean class="com.lchml.webcat.config.WebcatWsConf" id="webcatConf">
    <property name="heartbeat" value="15"/>
    <property name="useProxy" value="false"/>
    <property name="logResponse" value="true"/>
    <property name="logEnable" value="true"/>
</bean>

websocket模式,采用json格式做协议交互,格式如下:

{
    "path": "/test/hello", // 请求的path,对应controller中的path
    "mid": 1, // 请求的序号,用于对应请求和回包
    "version": 0, // 版本号,可不用
    "params": {"name": "holyshit"} // 业务的参数
}

所有的请求最后都会被组装为WsContext对象:

public class WsContext {
    private String path;

    private ChannelInfo ci;

    private int mid;

    private int version;

    private Channel channel;

    private Map<String, Object> params;
}

其中,ChannelInfo中会包含请求方的客户端ip,并且可以在ChannelConnectListener中自定义其他属性,params默认会根据Controller中方法定义映射到对应的参数上。

其他补充

项目结构截图如下


webcat——基于netty的http和websocket框架

代码地址如下:
http://www.demodashi.com/demo/12687.html

注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

posted on   demo例子集  阅读(3298)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示