netty 和webSocket 做一个及时通讯(二)

最新的效果如下面:


微信截图_20210618170108.png

前言
接webSocket 练习进行留下来demo,之前ui 进行的修改。
用netty 做了socket 的功能。

html 界面 代码


netty
<p>登录</p>
<input type="text" id="userinfo"/>
<input type="button" value="登录" onclick="CHAT.login()"/>

<div>发送消息:</div>
发送给谁
<input type="text" id="receivername"/>
发送内容
<input type="text" id="msgContent"/>
<input type="button" value="点我发送" onclick="CHAT.chat()"/>

<div>接受消息:</div>
<div id="receiveMsg" style="background-color: gainsboro;"></div>

<script type="application/javascript">

    window.CHAT = {
        socket: null,
        init: function () {
            if (window.WebSocket) {
                CHAT.socket = new WebSocket("ws://192.168.1.191:8088/ws");
                CHAT.socket.onopen = function () {
                    console.log("连接建立成功...");
                },
                    CHAT.socket.onclose = function () {
                        console.log("连接关闭...");
                    },
                    CHAT.socket.onerror = function () {
                        console.log("发生错误...");
                    },
                    CHAT.socket.onmessage = function (e) {
                        console.log("接受到消息:" + e.data);
                        var receiveMsg = document.getElementById("receiveMsg");
                        var html = receiveMsg.innerHTML;
                        receiveMsg.innerHTML = html + "<br/>" + e.data;
                    }
            } else {
                alert("浏览器不支持websocket协议...");
            }
        },
        chat: function () {
            var userinfo = document.getElementById("userinfo");
            var msg = document.getElementById("msgContent");
            var receivername = document.getElementById("receivername");
            var txt = "{" +
                "\"active\":1," +
                "\"username\":\"" + userinfo.value + "\"," +
                "\"receivername\":\"" + receivername.value + "\"," +
                "\"msg\":\"" + msg.value + "\"" +
                "}"
            CHAT.socket.send(txt);
        },
        login: function () {
            var userinfo = document.getElementById("userinfo");
            var txt = "{" +
                "\"active\":0," +
                "\"username\":\"" + userinfo.value + "\"," +
                "\"receivername\":\"\"," +
                "\"msg\":\"\"" +
                "}"
            CHAT.socket.send(txt);
        }
    };

    CHAT.init();

</script>
</body>
</html>

只有登录和发送两个状态

private int active;                 // 0 是登录1 是发送

点击和发送 功能 就是json 之间传输就可以了。。
后台代码

 <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>

spring boot 项目,创建一个新的就行。

netty 需要自己启动。。
所以写了一个自己启动功能

@Component
//如果有多个runner需要指定一些顺序
@Order(1)
public class NettyRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("netty 启动了...");
        /*websocket 中使用 需要启动这个*/
        WSServer.WSServerRun();
    }
}

发送给用户主要是

 channel.writeAndFlush(
                new TextWebSocketFrame(content));

获取保留channel 来发送 消息的。json 数据或其他类型 数据流转的。

发送主要的方法


 @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg)
            throws Exception {
        // 获取客户端传输过来的消息
        String content = msg.text();
        Channel channel = ctx.channel();
        System.out.println("接受到的数据:" + content);
        // 1. 获取客户端发来的消息
        UserLogin userLogin = JsonUtils.jsonToPojo(content, UserLogin.class);
        if (userLogin == null) {
            return;
        }
        int active = userLogin.getActive();
        switch (active) {
            case 0:
                UserChannelUtils.put(userLogin.getUsername(), channel);
                UserChannelUtils.sendMessage(channel,
                        "[服务器在]" + LocalDateTime.now()
                                + "接受到消息, 登录成功");
                break;
            case 1:
                Channel channel1 = UserChannelUtils.get(userLogin.getReceivername());
                if (channel1 == null) {
                    UserChannelUtils.sendMessage(channel,
                            "[服务器在]" + LocalDateTime.now()
                                    + "您的好友没有登录");
                } else {

                    UserChannelUtils.sendMessage(channel,
                            "[服务器在]" + LocalDateTime.now()
                                    + "发送成功");

                    UserChannelUtils.sendMessage(channel1,
                            "[服务器在]" + LocalDateTime.now()
                                    + "您的好友" + userLogin.getUsername() + "给您发送内容是:" + userLogin.getMsg());
                }


                break;
        }

    }

后台效果

微信截图_20210618172237.png

推荐阅读更多精彩内容