日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

微信小程序與Netty實(shí)現(xiàn)的WebSocket聊天程序

作者:老鐘私房菜 更新時(shí)間: 2022-10-11 編程語(yǔ)言

一、微信小程序?qū)崿F(xiàn)WebSocket客戶端程序

1. 界面實(shí)現(xiàn)

<input name="url" value="{{url}}" bindinput ="urlInput"/>
<button size='mini' type="warn">斷開(kāi)連接</button>
<button size='mini' type="primary" bindtap="connectSocket">開(kāi)啟連接</button>
<textarea placeholder="輸入發(fā)送內(nèi)容" bindinput ="msgInput"></textarea>
<button size='mini' type="primary" bindtap="sendMsg">發(fā)送</button>
<view wx:for="{{msgs}}">{{index}}: {{item}}</view>

界面效果:
在這里插入圖片描述

2. WXS部分

Page({
  data: {
    url: 'ws://localhost:8888/ws',
    msgs: [],
    msg: '',
  }
  // 連接WebSocket服務(wù)  
  connectSocket() {    
    let _this = this;    
    // 連接websocket服務(wù)    
    let task = wx.connectSocket({      
      url: _this.data.url    
    });    
    // 監(jiān)聽(tīng)websocket消息,并將接收到的消息添加到消息數(shù)組msgs中   
    task.onMessage(function(res) {       
      _this.setData({        
        msgs: [..._this.data.msgs, "接收到消息 -> " + res.data]      
      });    
    });    
    // 保存websocket實(shí)例     
    _this.setData({       
      socketTask: task,       
      msgs: [..._this.data.msgs,"連接成功!"]    
    });  
  },    
  
  // 獲取輸入內(nèi)容,并臨時(shí)保存在msg中  
  msgInput(e) {    
    this.setData({       
      msg: e.detail.value    
    });  
  },    
  
  // 發(fā)送消息  
  sendMsg() {    
    // 1.獲取輸入內(nèi)容    
    let msg = this.data.msg;    
    // 2.發(fā)送消息到WebSocket服務(wù)端    
    this.data.socketTask.send({      
      data: msg    
    });  
  }
})

二、Netty實(shí)現(xiàn)WebSocket服務(wù)端程序

1. 新建一個(gè)Maven工程,并引入Netty依賴

  • 項(xiàng)目目錄結(jié)構(gòu):

在這里插入圖片描述

  • 引入Netty依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.netty</groupId>
    <artifactId>NettyWebSocket</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.48.Final</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. 自定義處理器

  • 定義一個(gè)專門(mén)處理Http協(xié)議的處理器,當(dāng)瀏覽器第一次連接時(shí)候會(huì)讀取首頁(yè)的html文件,并將html文件內(nèi)容返回給瀏覽器展示。
package io.netty.websocket;

import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedNioFile;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;

// 處理Http協(xié)議的Handler,該Handler只會(huì)在第一次客戶端連接時(shí)候有用。
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private final String wsUri;
    private static final File INDEX;

    static {
        URL location = HttpRequestHandler.class.getProtectionDomain()
                .getCodeSource().getLocation();
        try {
            String path = location.toURI() + "index.html";
            path = !path.contains("file:") ? path : path.substring(5);
            INDEX = new File(path);
        } catch (URISyntaxException e) {
            throw new IllegalStateException("Unable to locate index.html", e);
        }
    }

    public HttpRequestHandler(String wsUri) {
        this.wsUri = wsUri;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 如果被請(qǐng)求的 URL 以/ws 結(jié)尾,那么我們將會(huì)把該協(xié)議升級(jí)為 WebSocket。
        if (wsUri.equalsIgnoreCase(request.getUri())) {
            // 將請(qǐng)求傳遞給下一個(gè)ChannelHandler,即WebSocketServerProtocolHandler處理
            // request.retain()會(huì)增加引用計(jì)數(shù)器,以防止資源被釋放
            ctx.fireChannelRead(request.retain());
            return;
        }
        handleHttpRequest(ctx, request);
    }

    /**
     * 該方法讀取首頁(yè)html文件內(nèi)容,然后將內(nèi)容返回給客戶端展示
     * @param ctx
     * @param request
     * @throws Exception
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // HTTP1.1協(xié)議允許客戶端先判定服務(wù)器是否愿意接受客戶端發(fā)來(lái)的消息主體,以減少由于服務(wù)器拒絕請(qǐng)求所帶來(lái)的額外資源開(kāi)銷
        if (HttpHeaders.is100ContinueExpected(request)) {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
            ctx.writeAndFlush(response);
        }
        // 從resources目錄讀取index.html文件
        RandomAccessFile file = new RandomAccessFile(INDEX, "r");
        // 準(zhǔn)備響應(yīng)頭信息
        HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
        boolean keepAlive = HttpHeaders.isKeepAlive(request);
        if (keepAlive) {
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length());
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        ctx.write(response);
        // 輸出html文件內(nèi)容
        ctx.write(new ChunkedNioFile(file.getChannel()));
        // 最后發(fā)送一個(gè)LastHttpContent來(lái)標(biāo)記響應(yīng)的結(jié)束
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        // 如果不是長(zhǎng)鏈接,則在寫(xiě)操作完成后關(guān)閉Channel
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
  • 定義一個(gè)專門(mén)處理WebSocket協(xié)議的處理器。
package io.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

// 處理WebSocket協(xié)議的Handler
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private final ChannelGroup channelGroup;

    public TextWebSocketFrameHandler(ChannelGroup channelGroup) {
        this.channelGroup = channelGroup;
    }

    // 用戶事件監(jiān)聽(tīng),每次客戶端連接時(shí)候自動(dòng)觸發(fā)
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        String content = "Client " + ctx.channel().remoteAddress().toString().substring(1) + " joined";
        System.out.println(content);
        // 如果是握手完成事件,則從Pipeline中刪除HttpRequestHandler,并將當(dāng)前channel添加到ChannelGroup中
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            // 從Pipeline中刪除HttpRequestHandler
            ctx.pipeline().remove(HttpRequestHandler.class);
            // 通知所有已連接的WebSocket客戶端,新的客戶端已經(jīng)連接上了
            TextWebSocketFrame msg = new TextWebSocketFrame(content);
            channelGroup.writeAndFlush(msg);
            // 將WebSocket Channel添加到ChannelGroup中,以便可以它接收所有消息
            channelGroup.add(ctx.channel());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    // 每次客戶端發(fā)送消息時(shí)執(zhí)行
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
        System.out.println("讀取到的消息:" + msg.retain());
        // 將讀取到的消息寫(xiě)到ChannelGroup中所有已經(jīng)連接的客戶端
        channelGroup.writeAndFlush(msg.retain());
    }
}

上面userEventTriggered方法監(jiān)聽(tīng)用戶事件。當(dāng)有客戶端連接時(shí)候,會(huì)自動(dòng)執(zhí)行該方法。而channelRead0方法負(fù)責(zé)讀取客戶端發(fā)送過(guò)來(lái)的消息,然后通過(guò)channelGroup將消息輸出到所有已連接的客戶端。

3. 定義初始化器

定義一個(gè)ChannelInitializer的子類,其主要目的是在某個(gè) Channel 注冊(cè)到 EventLoop 后,對(duì)這個(gè) Channel 執(zhí)行一些初始化操作。

package io.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class ChatServerInitializer extends ChannelInitializer<Channel> {
    private final ChannelGroup channelGroup;

    public ChatServerInitializer(ChannelGroup channelGroup) {
        this.channelGroup = channelGroup;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        // 安裝編解碼器,以實(shí)現(xiàn)對(duì)HttpRequest、 HttpContent、LastHttp-Content與字節(jié)之間的編解碼
        pipeline.addLast(new HttpServerCodec());
        // 專門(mén)處理寫(xiě)文件的Handler
        pipeline.addLast(new ChunkedWriteHandler());
        // Http聚合器,可以讓pipeline中下一個(gè)Channel收到完整的HTTP信息
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        // 處理Http協(xié)議的ChannelHandler,只會(huì)在客戶端第一次連接時(shí)候有用
        pipeline.addLast(new HttpRequestHandler("/ws"));
        // 升級(jí)Websocket后,使用該 ChannelHandler 處理Websocket請(qǐng)求
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // 安裝專門(mén)處理 Websocket TextWebSocketFrame 幀的處理器
        pipeline.addLast(new TextWebSocketFrameHandler(channelGroup));
    }
}

4. 創(chuàng)建啟動(dòng)類

package io.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

import java.net.InetSocketAddress;

public class ChatServer {

    public void start() {
        ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChatServerInitializer(channelGroup));
            ChannelFuture future = bootstrap.bind(new InetSocketAddress(8888)).syncUninterruptibly();
            System.out.println("Starting ChatServer on port 8888 ...");
            future.channel().closeFuture().syncUninterruptibly();
        } finally {
            channelGroup.close();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new ChatServer().start();
    }
}

5. 編寫(xiě)一個(gè)html文件

該html文件提供網(wǎng)頁(yè)版的WebSocket客戶端頁(yè)面。在src/main/resources目錄下新建一個(gè)html文件。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
</head>
<body>
<form οnsubmit="return false;">
    <h3>WebSocket 聊天室:</h3>
    <textarea id="responseText" style="width: 500px; height: 300px;"></textarea><br/>
    <input type="text" name="message"  style="width: 300px" value="Hello Netty"/>
    <input type="button" value="發(fā)送消息" onclick="send(this.form.message.value)"/>
    <input type="button" value="清空聊天記錄" onclick="clearScreen()"/>
</form>
<script type="text/javascript">
    var socket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8888/ws");
        // 注意:使用tls協(xié)議通信時(shí)候,協(xié)議名為wss
        // socket = new WebSocket("wss://localhost:8443/ws");
        socket.onopen = function(event) {
            var ta = document.getElementById('responseText');
            ta.value = "連接開(kāi)啟!";
        };
        socket.onclose = function(event) {
            var ta = document.getElementById('responseText');
            ta.value = ta.value + '\n' + "連接被關(guān)閉!";
        };
        socket.onmessage = function(event) {
            var ta = document.getElementById('responseText');
            ta.value = ta.value + '\n' + event.data;
        };
    } else {
        alert("你的瀏覽器不支持 WebSocket!");
    }

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("連接沒(méi)有開(kāi)啟.");
        }
    }

    function clearScreen() {
        document.getElementById('responseText').value = "";
    }
</script>
</body>
</html>

界面效果:
在這里插入圖片描述
最終效果:
在這里插入圖片描述

原文鏈接:https://blog.csdn.net/zhongliwen1981/article/details/127247243

欄目分類
最近更新