netty学习五:websocket小demo

概述


netty支持websocket,下面的demo用一个html作为客户端,对服务端发起websocket请求。


服务端代码


package websocket.server;

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;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class WebSocketServer {

    public static void main(String[] args) throws InterruptedException {
        // 接收连接,但是不处理
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        // 真正处理连接的group
        EventLoopGroup childGroup = new NioEventLoopGroup();

        try {
            //加载Initializer
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup, childGroup)
                           .channel(NioServerSocketChannel.class)
                           .handler(new  LoggingHandler(LogLevel.INFO))
                           .childHandler(new WebSocketServerInitializer());

            //绑定监听端口
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }
        finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}

package websocket.server;

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.stream.ChunkedWriteHandler;

public class WebSocketServerInitializer 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(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new WebSocketServerHandler());
    }
}

package websocket.server;

import java.time.LocalDateTime;

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

public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到的消息:"+msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:"+LocalDateTime.now()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded:"+ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved:"+ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生");
        ctx.close();
    }

}

客户端代码


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket 客户端</title>
</head>
<body>
    <script type="application/javascript">
    var socket;
    if (window.WebSocket) {
       socket = new WebSocket("ws://localhost:8899/ws");
       //当服务端发送消息给客户端时,该方法会被调用
       socket.onmessage = function (event) {
          var responseContent = document.getElementById("responseText");
           responseContent.value = responseContent.value + "\n" + event.data;
       };

       socket.onopen = function (event) {
           var responseContent = document.getElementById("responseText");
           responseContent.value = "连接建立了";
       };

        socket.onclose = function (event) {
            var responseContent = document.getElementById("responseText");
            responseContent.value = responseContent.value + "\n" + "连接断开了";
        }
    }
    else {
        alert('浏览器不支持websocket');
    }

    function send(message) {
        if (!window.WebSocket){
            return;
        }

        if (socket.readyState == WebSocket.OPEN) {
             socket.send(message);
        }
        else {
            alert('连接还未建立');
        }
    }
    </script>

    <form onsubmit="return false;">
        <textarea id="messageId" name="message" style="width: 400px; height: 200px"></textarea>

        <input type="button" value="发送按钮" onclick="send(document.getElementById('messageId').value)">

        <h3>服务端输出:</h3>

        <textarea id="responseText" name="message" style="width: 400px; height: 300px"></textarea>
    </form>
</body>
</html>

csdn code 路径


这个项目的源代码放置在csdn code上,欢迎访问。

netty_study

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值