netty4学习笔记5-netty作为WebSocket服务器

本文介绍如何使用Netty搭建WebSocket服务器,包括服务器启动程序、初始化程序及处理程序的编写过程。此外,还提供了HTML5客户端的实现代码。

需求:

编写一个WebSocket服务器,来完成读取客户端的请求,并完成相应

编写步骤:

1. 编写服务器端的启动程序

package com.baidu.netty.fouthExample;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new MyServerInitializer());
            ChannelFuture future = bootstrap.bind(8899).sync();
            future.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

2. 编写服务器端的初始化程序

package com.baidu.netty.fouthExample;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;

public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        /**以块的形式写*/
        pipeline.addLast(new ChunkedWriteHandler());
        /**将块组装成对象(比如该处用到的文本对象)*/
        pipeline.addLast(new HttpObjectAggregator(1024));
        /**添加对于websocket的支持,参数配置的是访问的路径*/
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new MyServerHandler());
    }
}

3. 编写服务器的处理程序

package com.baidu.netty.fouthExample;

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

public class MyServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("【客户端的消息】:" + msg.text());
        /**返回的时候也必须要是TextWebSocketFrame对象而不能是普通的字符串*/
        TextWebSocketFrame content = new TextWebSocketFrame("你好客户端");
        ctx.writeAndFlush(content);
    }

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

4. 编写html5的socket请求程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket访问netty</title>
    <script>
        var socket;
        if(window.WebSocket)
        {
            //第一个ws是协议,第二个ws是我们在pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); 配置的
            socket = new WebSocket("ws://localhost:8899/ws");
            //当socket得到数据的时候调用,相当于channelRead0
            socket.onmessage = function(event)
            {
                document.getElementById("content").value = event.data;
            }
            socket.onopen = function (ev) {
                document.getElementById("content").value = "客户端连上了服务器";
            }
            socket.onclose = function (ev) {
                document.getElementById("content").value = "客户端断开服务器";
            }
        }else
        {
            alert("当前浏览器不支持websocket程序");
        }

        function sendMsg() {
            if(socket && socket.readyState == WebSocket.OPEN)
            {
                socket.send(document.getElementById("content").value);
            }
        }
    </script>
</head>
<body>
<input value="发送" type="button" onclick="sendMsg()"><br>
<textarea id="content"></textarea>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值