【Netty学习】10.WebSocket通信实现


1 基于Stomp的聊天室IM 的实现

本应用基于Spring Boot搭建,版本2.1.5.RELEASE,依赖spring-boot-starter-websocket。前端采用thymeleaf,依赖JQueryStompSocketJS

1.1 流程图

Stomp聊天应用流程图

1.2 聊天界面

1.2.1 James聊天视角

Jams聊天视角

1.2.1 Mark聊天视角

Mark聊天视角

1.3 前端界面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="aplus-terminal" content="1">
<meta name="apple-mobile-web-app-title" content="">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="format-detection" content="telephone=no, address=no">
<title>聊天</title>
<style type="text/css">
    /*公共样式*/
    body,h1,h2,h3,h4,p,ul,ol,li,form,button,input,textarea,th,td {
        margin:0;
        padding:0
    }
    body,button,input,select,textarea {
        font:12px/1.5 Microsoft YaHei UI Light,tahoma,arial,"\5b8b\4f53";
        *line-height:1.5;
        -ms-overflow-style:scrollbar
    }
    h1,h2,h3,h4{
        font-size:100%
    }
    ul,ol {
        list-style:none
    }
    a {
     text-decoration:none
    }
    a:hover {
        text-decoration:underline
    }
    img {
        border:0
    }
    button,input,select,textarea {
        font-size:100%
    }
    table {
        border-collapse:collapse;
        border-spacing:0
    }

    /*rem*/
    html {
           font-size:62.5%;
     }
     body {
           font:16px/1.5 "microsoft yahei", 'tahoma';
     }
     body .mobile-page {
           font-size: 1.6rem;
     }

     /*浮动*/
    .fl{
        float: left;
     }
    .fr{
        float: right;
     }
    .clearfix:after{
        content: '';
        display: block;
        height: 0;
        clear: both;
        visibility: hidden;
    }

    body{
     background-color: #F5F5F5;
    }
    .mobile-page{
     max-width: 600px;
    }
    .mobile-page .admin-img, .mobile-page .user-img{
     width: 45px;
     height: 45px;
    }
    i.triangle-admin,i.triangle-user{
     width: 0;
         height: 0;
         position: absolute;
         top: 10px;
     display: inline-block;
         border-top: 10px solid transparent;
         border-bottom: 10px solid transparent;
    }
    .mobile-page i.triangle-admin{
     left: 4px;
     border-right: 12px solid #fff;
    }
    .mobile-page i.triangle-user{
     right: 4px;
         border-left: 12px solid #9EEA6A;
    }
    .mobile-page .admin-group, .mobile-page .user-group{
     padding: 6px;
     display: flex;
     display: -webkit-flex;
    }
    .mobile-page .admin-group{
     justify-content: flex-start;
     -webkit-justify-content: flex-start;
    }
    .mobile-page .user-group{
     justify-content: flex-end;
     -webkit-justify-content: flex-end;
    }
    .mobile-page .admin-reply, .mobile-page .user-reply{
     display: inline-block;
     padding: 8px;
     border-radius: 4px;
     background-color: #fff;
     margin:0 15px 12px;
    }
    .mobile-page .admin-reply{
     box-shadow: 0px 0px 2px #ddd;
    }
    .mobile-page .user-reply{
     text-align: left;
     background-color: #9EEA6A;
     box-shadow: 0px 0px 2px #bbb;
    }
    .mobile-page .user-msg, .mobile-page .admin-msg{
     width: 75%;
     position: relative;
    }
    .mobile-page .user-msg{
     text-align: right;
    }
    .chatRecord{
        width: 100%;
        height: 400px;
        border-bottom: 1px solid blue;
        line-height:20px;
        overflow:auto;
        overflow-x:hidden;
    }
</style>
</head>
<body>
<div>
    <div style="float:left;width:47%">
        <p>请选择你是谁:
        <select id="selectName" onchange="stompQueue();">
            <option value="1">请选择</option>
            <option value="Mark">Mark</option>
            <option value="James">James</option>
            <option value="Lison">Lison</option>
            <option value="Peter">Peter</option>
            <option value="King">King</option>
        </select>
        </p>
        <div class="chatWindow">
            <p style="color:darkgrey">群聊:</p>
            <section id="chatRecord1" class="chatRecord">
                <div id="mass_div" class="mobile-page">

                </div>
            </section>
            <section class="sendWindow">
                <textarea name="sendChatValue" id="sendChatValue" class="sendChatValue"></textarea>
                <input type="button" name="sendMessage" id="sendMassMessage" class="sendMessage" onclick="sendMassMessage()" value="发送">
            </section>
        </div>
    </div>


    <div style="float:right; width:47%">
        <p>请选择你要发给谁:
        <select id="selectName2">
            <option value="1">请选择</option>
            <option value="Mark">Mark</option>
            <option value="James">James</option>
            <option value="Lison">Lison</option>
            <option value="Peter">Peter</option>
            <option value="King">King</option>
        </select>
        </p>
        <div class="chatWindow">

            <p style="color:darkgrey">单聊:</p>
            <section id="chatRecord2" class="chatRecord">
                <div id="alone_div"  class="mobile-page">

                </div>
            </section>
            <section class="sendWindow">
                <textarea name="sendChatValue2" id="sendChatValue2" class="sendChatValue"></textarea>
                <input type="button" name="sendMessage" id="sendAloneMessage" class="sendMessage" onclick="sendAloneMessage()" value="发送">
            </section>
        </div>
    </div>
</div>

<!-- 独立JS -->
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
<script th:src="@{wechat_room.js}"></script>
</body>
</html>

1.4 配置

1.4.1 WebSocketConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author zyxelva
 * @description 类说明:开启使用Stomp协议来传输基于消息broker的消息
 * 这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 注册STOMP协议的节点(endpoint),并映射指定的url,
     * 添加一个访问端点“/endpointMark”,客户端打开双通道时需要的url,
     * 允许所有的域名跨域访问,指定使用SockJS协议。
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpointMark").setAllowedOrigins("*").withSockJS();
    }

    /**
     * 配置Broker
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/mass", "/user");
        registry.setUserDestinationPrefix("/user/");
    }

}

1.4.2 WebMvcConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zyxelva
 * @description webmvc配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/chatroom").setViewName("/wechat_room");
    }

}

1.4.3 wechat_room.js

var stompClient = null;

//加载完浏览器后调用connect(),打开通道
$(function(){
    //打开双通道
    connect()
})

//强制关闭浏览器时调用websocket.close(),进行正常关闭
window.onunload = function() {
    disconnect()
}

//打开通道
function connect(){
    var socket = new SockJS('/endpointMark'); //连接SockJS的endpoint名称为"endpointMark"
    stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
    stompClient.connect({},function(frame){//连接WebSocket服务端

        console.log('Connected:' + frame);
        //接收广播信息
        stompTopic();

    });
}

//关闭通道
function disconnect(){
    if(stompClient != null) {
        stompClient.disconnect();
    }
    console.log("Disconnected");
}

//一对多,发起订阅
function stompTopic(){
    //通过stompClient.subscribe订阅目标(destination)发送的消息(广播接收信息)
    stompClient.subscribe('/mass/getResponse',function(response){
        var message=JSON.parse(response.body);
        //展示广播的接收的内容接收
        var response = $("#mass_div");
        var userName=$("#selectName").val();
        if(userName==message.name){
            response.append("<div class='user-group'>" +
                "          <div class='user-msg'>" +
                "                <span class='user-reply'>"+message.chatValue+"</span>" +
                "                <i class='triangle-user'></i>" +
                "          </div>" +userName+
                "     </div>");
        }else{
            response.append("     <div class='admin-group'>"+
                message.name+
                "<div class='admin-msg'>"+
                "    <i class='triangle-admin'></i>"+
                "    <span class='admin-reply'>"+message.chatValue+"</span>"+
                "</div>"+
                "</div>");
        }
    });
}

//群发消息
function sendMassMessage(){
    var postValue={};
    var chatValue=$("#sendChatValue");
    var userName=$("#selectName").val();
    postValue.name=userName;
    postValue.chatValue=chatValue.val();
    //postValue.userId="0";
    if(userName==1||userName==null){
        alert("请选择你是谁!");
        return;
    }
    if(chatValue==""||userName==null){
        alert("不能发送空消息!");
        return;
    }
    stompClient.send("/massRequest",{},JSON.stringify(postValue));
    chatValue.val("");
}

//单独发消息
function sendAloneMessage(){
    var postValue={};
    var chatValue=$("#sendChatValue2");
    var userName=$("#selectName").val();
    var sendToId=$("#selectName2").val();
    var response = $("#alone_div");
    postValue.name=userName;//发送者姓名
    postValue.chatValue=chatValue.val();//聊天内容
    postValue.userId=sendToId;//发送给谁
    if(userName==1||userName==null){
        alert("请选择你是谁!");
        return;
    }
    if(sendToId==1||sendToId==null){
        alert("请选择你要发给谁!");
        return;
    }
    if(chatValue==""||userName==null){
        alert("不能发送空消息!");
        return;
    }
    stompClient.send("/aloneRequest",{},JSON.stringify(postValue));
    response.append("<div class='user-group'>" +
        "          <div class='user-msg'>" +
        "                <span class='user-reply'>"+chatValue.val()+"</span>" +
        "                <i class='triangle-user'></i>" +
        "          </div>" +userName+
        "     </div>");
    chatValue.val("");
}

//一对一,发起订阅
function stompQueue() {
    var userId = $("#selectName").val();
    //通过stompClient.subscribe订阅目标(destination)发送的消息(队列接收信息)
    stompClient.subscribe('/user/' + userId + '/alone',
        function (response) {
            var message = JSON.parse(response.body);
            //展示一对一的接收的内容接收
            var response = $("#alone_div");
            response.append("     <div class='admin-group'>" +
                message.name +
                "<div class='admin-msg'>" +
                "    <i class='triangle-admin'></i>" +
                "    <span class='admin-reply'>" + message.chatValue + "</span>" +
                "</div>" +
                "</div>");
        });
}

1.5 Controller

import cn.enjoyedu.stomp.domain.ChatRoomRequest;
import cn.enjoyedu.stomp.domain.ChatRoomResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;

/**
 * @author zyxelva
 * @description 在线聊天室
 */
@Controller
public class StompController {
    /**
     * Spring实现的一个发送模板类
     */
    @Autowired
    private SimpMessagingTemplate template;

    /**
     * 消息群发,接受发送至自massRequest的请求
     */
    @MessageMapping("/massRequest")
    @SendTo("/mass/getResponse")
    public ChatRoomResponse mass(ChatRoomRequest chatRoomRequest) {
        System.out.println("name = " + chatRoomRequest.getName());
        System.out.println("chatValue = " + chatRoomRequest.getChatValue());
        ChatRoomResponse response = new ChatRoomResponse();
        response.setName(chatRoomRequest.getName());
        response.setChatValue(chatRoomRequest.getChatValue());
        return response;
    }

    /**
     * 单独聊天,接受发送至自aloneRequest的请求
     */
    @MessageMapping("/aloneRequest")
    public ChatRoomResponse alone(ChatRoomRequest chatRoomRequest) {
        System.out.println("SendToUser = " + chatRoomRequest.getUserId() + " FromName = " + chatRoomRequest.getName() + " ChatValue = " + chatRoomRequest.getChatValue());
        ChatRoomResponse response = new ChatRoomResponse();
        response.setName(chatRoomRequest.getName());
        response.setChatValue(chatRoomRequest.getChatValue());
        this.template.convertAndSendToUser(chatRoomRequest.getUserId() + "", "/alone", response);
        return response;
    }
}

1.6 聊天室的请求实体

/**
 * @author zyxelva
 * @description 聊天室的请求实体
 */
public class ChatRoomRequest {
    private String name;
    private String chatValue;
    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getChatValue() {
        return chatValue;
    }

    public void setChatValue(String chatValue) {
        this.chatValue = chatValue;
    }
}

2 原生WebSocket聊天应用(群聊)

2.1 A用户视角

A用户视角

2.2 B用户视角

B用户视角

2.3 Socket Server

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
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.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.concurrent.ImmediateEventExecutor;

/**
 * @author zyxelva
 * @description socket server
 */
public final class WebSocketServer {

    /**
     * 创建 DefaultChannelGroup,用来保存所
     * 有已经连接的 WebSocket Channel,群发和一对一功能可以用上
     */
    private final static ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    /**
     * 是否启用ssl
     */
    static final boolean SSL = false;
    /**
     * 通过ssl访问端口为8443,否则为8080
     */
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8443" : "8080"));

    public static void main(String[] args) throws Exception {
        /*SSL配置*/
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new WebSocketServerInitializer(sslCtx, CHANNEL_GROUP));

            Channel ch = b.bind(PORT).sync().channel();

            System.out.println("打开浏览器访问: " + (SSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/');

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

2.4 Socket Server Initializer

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.socket.SocketChannel;
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.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.ssl.SslContext;

/**
 * @author zyxelva
 * @description socket server initializer
 */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * websocket访问路径
     */
    private static final String WEBSOCKET_PATH = "/websocket";

    private final ChannelGroup group;

    private final SslContext sslCtx;

    public WebSocketServerInitializer(SslContext sslCtx, ChannelGroup group) {
        this.sslCtx = sslCtx;
        this.group = group;
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        if (sslCtx != null) {
            pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        }
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));

        /*支持ws数据的压缩传输*/
        pipeline.addLast(new WebSocketServerCompressionHandler());

        pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));

        /*浏览器访问的时候展示index页面*/
        pipeline.addLast(new ProcessWsIndexPageHandler(WEBSOCKET_PATH));

        /*对WS的数据进行处理*/
        pipeline.addLast(new ProcessWsFrameHandler(group));

    }
}

2.5 Handler

2.5.1 ProcessWsIndexPageHandler

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @author zyxelva
 * @description 对http请求,将index的页面返回给前端
 */
public class ProcessWsIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final String websocketPath;

    public ProcessWsIndexPageHandler(String websocketPath) {
        this.websocketPath = websocketPath;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        // 处理错误或者无法解析的http请求
        if (!req.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
            return;
        }

        //只允许Get请求
        if (req.method() != GET) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
            return;
        }

        // 发送index页面的内容
        if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) {
            //生成WebSocket的访问地址,写入index页面中
            String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
            System.out.println("WebSocketLocation:[" + webSocketLocation + "]");
            //生成index页面的具体内容,并送往浏览器
            ByteBuf content = MakeIndexPage.getContent(webSocketLocation);
            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

            res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
            HttpUtil.setContentLength(res, content.readableBytes());

            sendHttpResponse(ctx, req, res);
        } else {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 发送应答
     */
    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // 错误的请求进行处理 (code<>200).
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        // 发送应答.
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        //对于不是长连接或者错误的请求直接关闭连接
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    /**
     * 根据用户的访问,告诉用户的浏览器,WebSocket的访问地址
     */
    private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
        String protocol = "ws";
        if (cp.get(SslHandler.class) != null) {
            protocol = "wss";
        }
        return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
    }
}

2.5.2 ProcessWsFrameHandler

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.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Locale;

/**
 * @author zyxelva
 * @description 对websocket的数据进行处理
 */
public class ProcessWsFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private final ChannelGroup group;

    public ProcessWsFrameHandler(ChannelGroup group) {
        this.group = group;
    }

    private static final Logger logger = LoggerFactory.getLogger(ProcessWsFrameHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame) {
            String request = ((TextWebSocketFrame) frame).text();
            ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.CHINA)));
            /*群发*/
            group.writeAndFlush(new TextWebSocketFrame("Client" + ctx.channel() + "say:" + request.toUpperCase(Locale.CHINA)));

        } else {
            throw new UnsupportedOperationException("unsupport data frame");
        }
    }

    /**
     * 重写 userEventTriggered()方法以处理自定义事件
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        /*检查事件类型,如果是ws握手成功事件,群发通知*/
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            group.writeAndFlush(new TextWebSocketFrame("Client" + ctx.channel() + " joined"));
            group.add(ctx.channel());

        }
    }
}

2.5.3 MakeIndexPage

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * @author Mark老师   享学课堂 https://enjoy.ke.qq.com
 * 类说明:生成index页面的内容
 */
public final class MakeIndexPage {

    private static final String NEWLINE = "\r\n";

    public static ByteBuf getContent(String webSocketLocation) {
        return Unpooled.copiedBuffer(
                "<html><head><title>Web Socket Test</title></head>"
                        + NEWLINE +
                        "<body>" + NEWLINE +
                        "<script type=\"text/javascript\">" + NEWLINE +
                        "var socket;" + NEWLINE +
                        "if (!window.WebSocket) {" + NEWLINE +
                        "  window.WebSocket = window.MozWebSocket;" + NEWLINE +
                        '}' + NEWLINE +
                        "if (window.WebSocket) {" + NEWLINE +
                        "  socket = new WebSocket(\"" + webSocketLocation + "\");"
                        + NEWLINE +
                        "  socket.onmessage = function(event) {" + NEWLINE +
                        "    var ta = document.getElementById('responseText');"
                        + NEWLINE +
                        "    ta.value = ta.value + '\\n' + event.data" + NEWLINE +
                        "  };" + NEWLINE +
                        "  socket.onopen = function(event) {" + NEWLINE +
                        "    var ta = document.getElementById('responseText');"
                        + NEWLINE +
                        "    ta.value = \"Web Socket opened!\";" + NEWLINE +
                        "  };" + NEWLINE +
                        "  socket.onclose = function(event) {" + NEWLINE +
                        "    var ta = document.getElementById('responseText');"
                        + NEWLINE +
                        "    ta.value = ta.value + \"Web Socket closed\"; "
                        + NEWLINE +
                        "  };" + NEWLINE +
                        "} else {" + NEWLINE +
                        "  alert(\"Your browser does not support Web Socket.\");"
                        + NEWLINE +
                        '}' + NEWLINE +
                        NEWLINE +
                        "function send(message) {" + NEWLINE +
                        "  if (!window.WebSocket) { return; }" + NEWLINE +
                        "  if (socket.readyState == WebSocket.OPEN) {" + NEWLINE +
                        "    socket.send(message);" + NEWLINE +
                        "  } else {" + NEWLINE +
                        "    alert(\"The socket is not open.\");" + NEWLINE +
                        "  }" + NEWLINE +
                        '}' + NEWLINE +
                        "</script>" + NEWLINE +
                        "<form onsubmit=\"return false;\">" + NEWLINE +
                        "<input type=\"text\" name=\"message\" " +
                        "value=\"Hello, World!\"/>" +
                        "<input type=\"button\" value=\"Send Web Socket Data\""
                        + NEWLINE +
                        "       onclick=\"send(this.form.message.value)\" />"
                        + NEWLINE +
                        "<h3>Output</h3>" + NEWLINE +
                        "<textarea id=\"responseText\" " +
                        "style=\"width:500px;height:300px;\"></textarea>"
                        + NEWLINE +
                        "</form>" + NEWLINE +
                        "</body>" + NEWLINE +
                        "</html>" + NEWLINE, CharsetUtil.US_ASCII);
    }

}

2.6 Socket Client

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * @author zyxelva
 * @description 这是WebSocket客户端的示例。
 * 要运行此示例,需要兼容的WebSocket服务器。
 * 因此,可以通过运行WebSocketServer来启动WebSocket服务器,
 */
public final class WebSocketClient {

    static final String URL = System.getProperty("url", "ws://127.0.0.1:8080/websocket");
    static final String SURL = System.getProperty("url", "wss://127.0.0.1:8443/websocket");

    public static void main(String[] args) throws Exception {
        URI uri = new URI(URL);
        String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final String host =
                uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final int port = uri.getPort();

        if (!"ws".equalsIgnoreCase(scheme)
                && !"wss".equalsIgnoreCase(scheme)) {
            System.err.println("Only WS(S) is supported.");
            return;
        }

        final boolean ssl = "wss".equalsIgnoreCase(scheme);
        final SslContext sslCtx;
        if (ssl) {
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
            // If you change it to V00, ping is not supported and remember to change
            // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
            final WebSocketClientHandler handler =
                    new WebSocketClientHandler(
                            WebSocketClientHandshakerFactory
                                    .newHandshaker(
                                            uri, WebSocketVersion.V13,
                                            null,
                                            true,
                                            new DefaultHttpHeaders()));

            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc(),
                                        host, port));
                            }
                            p.addLast(
                                    //http协议为握手必须
                                    new HttpClientCodec(),
                                    new HttpObjectAggregator(8192),
                                    //支持WebSocket数据压缩
                                    WebSocketClientCompressionHandler.INSTANCE,
                                    handler);
                        }
                    });

            //连接服务器
            Channel ch = b.connect(uri.getHost(), port).sync().channel();
            //等待握手完成
            handler.handshakeFuture().sync();

            BufferedReader console = new BufferedReader(
                    new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(
                            Unpooled.wrappedBuffer(new byte[]{8, 1, 8, 1}));
                    ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}

2.7 Socket client handler

import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;

/**
 * @author zyxelva
 * @description socket client handler
 */
public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    /**
     * 负责和服务器进行握手
     */
    private final WebSocketClientHandshaker handshaker;
    /**
     * 握手的结果
     */
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    /**
     * 当前Handler被添加到ChannelPipeline时,new出握手的结果的实例,以备将来使用
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    /**
     * 通道建立,进行握手
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    /**
     * 通道关闭
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("WebSocket Client disconnected!");
    }

    /**
     * 读取数据
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        //握手未完成,完成握手
        if (!handshaker.isHandshakeComplete()) {
            try {
                handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                System.out.println("WebSocket Client connected!");
                handshakeFuture.setSuccess();
            } catch (WebSocketHandshakeException e) {
                System.out.println("WebSocket Client failed to connect");
                handshakeFuture.setFailure(e);
            }
            return;
        }

        //握手已经完成,升级为了websocket,不应该再收到http报文
        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
        }

        //处理websocket报文
        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            System.out.println("WebSocket Client received message: " + textFrame.text());
        } else if (frame instanceof PongWebSocketFrame) {
            System.out.println("WebSocket Client received pong");
        } else if (frame instanceof CloseWebSocketFrame) {
            System.out.println("WebSocket Client received closing");
            ch.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
    }
}

文章作者: Kezade
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Kezade !
评论
  目录