美文网首页
Netty4 之 简单搭建WebSocket服务

Netty4 之 简单搭建WebSocket服务

作者: yichen_china | 来源:发表于2021-10-25 14:35 被阅读0次

    搭建一个Netty服务器,我们只需要两个类——一个是启动类,负责启动(BootStrap)和main方法,一个是ChannelHandler,负责具体的业务逻辑,我们先从启动类说起。

    <dependency>
            <groupId>org.yeauty</groupId>
            <artifactId>netty-websocket-spring-boot-starter</artifactId>
            <version>0.12.0</version>
    </dependency>
    

    在端点类上加上@ServerEndpoint注解,并在相应的方法上加上@BeforeHandshake、@OnOpen、@OnClose、@OnError、@OnMessage、@OnBinary、@OnEvent注解,样例如下:

    package com.ruoyi.beiyao.message.config;
    import io.netty.handler.codec.http.HttpHeaders;
    import io.netty.handler.timeout.IdleStateEvent;
    import org.springframework.util.MultiValueMap;
    import org.yeauty.annotation.*;
    import org.yeauty.pojo.Session;
    
    import java.io.IOException;
    import java.util.Map;
    
    @ServerEndpoint(path = "/ws/{arg}",port = "${ws.port}")
    public class MyWebSocket {
    
        @BeforeHandshake
        public void handshake(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
            session.setSubprotocols("stomp");
            if (!"ok".equals(req)){
                System.out.println("Authentication failed!");
                session.close();
            }
        }
        
        @OnOpen
        public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
            System.out.println("new connection");
            System.out.println(req);
        }
    
        @OnClose
        public void onClose(Session session) throws IOException {
           System.out.println("one connection closed"); 
        }
    
        @OnError
        public void onError(Session session, Throwable throwable) {
            throwable.printStackTrace();
        }
    
        @OnMessage
        public void onMessage(Session session, String message) {
            System.out.println(message);
            session.sendText("Hello Netty!");
        }
    
        @OnBinary
        public void onBinary(Session session, byte[] bytes) {
            for (byte b : bytes) {
                System.out.println(b);
            }
            session.sendBinary(bytes); 
        }
    
        @OnEvent
        public void onEvent(Session session, Object evt) {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
                switch (idleStateEvent.state()) {
                    case READER_IDLE:
                        System.out.println("read idle");
                        break;
                    case WRITER_IDLE:
                        System.out.println("write idle");
                        break;
                    case ALL_IDLE:
                        System.out.println("all idle");
                        break;
                    default:
                        break;
                }
            }
        }
    
    }
    

    启动类没特殊需求

    public class BeiyaoMessageApplication {
    
        public static void main(String[] args)
        {
    
            SpringApplication.run(BeiyaoMessageApplication.class, args);
    
            System.out.println("(♥◠‿◠)ノ゙ 消息模块启动成功   ლ(´ڡ`ლ)゙  \n");
    
        }
    }
    

    配置文件
    bootstrap.yml

    # Tomcat http服务
    server:
      port: 9920
    # Spring
    spring: 
    #任意IP可以进行访问 websocket服务
    ws:
      host: 0.0.0.0
    #配置路径(自己使用发现配置路径有问题,采用/即为原生的配置没有问题)
      path: /
    #配置端口号
      port: 5656
    

    使用HTML5作为websocket前端实现

    index.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <script type="text/javascript">
            var socket;
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }
            if (window.WebSocket) {
                socket = new WebSocket("ws://localhost:8844/ws");
                socket.onmessage = function(event) {
                    var ta = document.getElementById('responseText');
                    ta.value = ta.value + '\n' + event.data
                };
                socket.onopen = function(event) {
                    var ta = document.getElementById('responseText');
                    ta.value = "连接开启!";
                };
                socket.onclose = function(event) {
                    var ta = document.getElementById('responseText');
                    ta.value = ta.value + "连接被关闭";
                };
            } else {
                alert("你的浏览器不支持!");
            }
     
            function send(message) {
                if (!window.WebSocket) {
                    return;
                }
                if (socket.readyState == WebSocket.OPEN) {
                    socket.send(message);
                } else {
                    alert("连接没有开启.");
                }
            }
        </script>
        <form onsubmit="return false;">
            <input type="text" name="message" value="Hello, World!"><input
                type="button" value="发送消息"
                onclick="send(this.form.message.value)">
            <h4>输出:</h4>
            <textarea id="responseText" ></textarea>
            <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空">
        </form>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:Netty4 之 简单搭建WebSocket服务

          本文链接:https://www.haomeiwen.com/subject/lagjaltx.html