java netty websocket server and html javascript websokcet client demo

论坛 期权论坛 脚本     
匿名技术用户   2020-12-27 20:55   580   0

目录

java code:

启动类:

初始化类:

通道类:

html code

前段代码

页面图片:

日志:

总结介绍:



pom.xmo include jar

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

java code:

启动类:


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;

/**
 * netty websocket
 * 
 * @author Administrator
 *
 */
public class WebsocketServer {
 public static void main(String[] args) throws InterruptedException {
  EventLoopGroup bossGroup = new NioEventLoopGroup();
  EventLoopGroup workerGroup = new NioEventLoopGroup();

  try {
   ServerBootstrap serverBootstrap = new ServerBootstrap();
   serverBootstrap.group(bossGroup, workerGroup)
     .channel(NioServerSocketChannel.class)
     .handler(new LoggingHandler(LogLevel.INFO))
     .childHandler(new WebSocketChannelInitializer());

   ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
   channelFuture.channel().closeFuture().sync();
  } finally {
   bossGroup.shutdownGracefully();
   workerGroup.shutdownGracefully();
  }
 }
}

初始化类:


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 WebSocketChannelInitializer extends
  ChannelInitializer<SocketChannel> {

 @Override
 protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  // HttpServerCodec: 针对http协议进行编解码
  pipeline.addLast("httpServerCodec", new HttpServerCodec());
  // ChunkedWriteHandler分块写处理,文件过大会将内存撑爆
  pipeline.addLast("chunkedWriteHandler", new ChunkedWriteHandler());
  /**
   * 作用是将一个Http的消息组装成一个完成的HttpRequest或者HttpResponse,那么具体的是什么 取决于是请求还是响应,
   * 该Handler必须放在HttpServerCodec后的后面
   */
  pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(8192));

  // 用于处理websocket, /ws为访问websocket时的uri
  pipeline.addLast("webSocketServerProtocolHandler", new WebSocketServerProtocolHandler("/ws"));

  pipeline.addLast("myWebSocketHandler", new WebSocketHandler());
 }
}

通道类:


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

import java.time.LocalDateTime;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + ": " + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("来自服务端: " + LocalDateTime.now()));
    }
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("ChannelId" + ctx.channel().id().asLongText());
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户下线: " + ctx.channel().id().asLongText());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}

html code

前段代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>netwebsocketClient</title>
</head>

<body>
    <form onsubmit="return false" style="border:1px solid #000;padding: 5px; width:500px;">
        <span><h2  style="margin-left:80px;">NettyWebSocketClientTest</h2></span>
        <h3>发送内容</h3>
        <textarea style="width: 300px; height: 200px;" name="message"></textarea>
        <input type="button" onclick="sendMsg(this.form.message.value)" value="发送"><br>
        <h3>消息</h3>
        <textarea style="width: 300px; height: 200px;" id="respMessage"></textarea>
        <input type="button" value="清空" onclick="javascript:document.getElementById('respMessage').value = ''">
    </form>
</body>
<script type="text/javascript">
    var websocket;

    //如果浏览器支持WebSocket
    if (window.WebSocket) {
        websocket = new WebSocket("ws://localhost:9999/ws");  //获得WebSocket对象

        //当有消息过来的时候触发
        websocket.onmessage = function (event) {
            var respMessage = document.getElementById("respMessage");
            respMessage.value = respMessage.value + "\n" + event.data;
        }

        //连接关闭的时候触发
        websocket.onclose = function (event) {
            var respMessage = document.getElementById("respMessage");
            respMessage.value = respMessage.value + "\n断开连接";
        }

        //连接打开的时候触发
        websocket.onopen = function (event) {
            var respMessage = document.getElementById("respMessage");
            respMessage.value = "建立连接";
        }
    } else {
        alert("浏览器不支持WebSocket");
    }

    function sendMsg(msg) { //发送消息 
        if (window.WebSocket) {
            if (websocket.readyState == WebSocket.OPEN) { //如果WebSocket是打开状态
                websocket.send(msg); //send()发送消息
            }
        } else {
            return;
        }
    }
</script>

</html>

页面图片:

日志:

21:55:29.410 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x68ceae04, L:/0:0:0:0:0:0:0:0:9999] READ: [id: 0x79ac2f78, L:/0:0:0:0:0:0:0:1:9999 - R:/0:0:0:0:0:0:0:1:60125]
21:55:29.410 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x68ceae04, L:/0:0:0:0:0:0:0:0:9999] READ COMPLETE
ChannelId00000000000000e0-00001ef8-00000016-d02f897192e1fe02-79ac2f78
21:55:29.413 [nioEventLoopGroup-3-6] DEBUG io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker - [id: 0x79ac2f78, L:/0:0:0:0:0:0:0:1:9999 - R:/0:0:0:0:0:0:0:1:60125] WebSocket version V13 server handshake
21:55:29.413 [nioEventLoopGroup-3-6] DEBUG io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker - WebSocket version 13 server handshake key: maAo4fEjermRPnmAK6BheA==, response: APIPEtlUWOcsvYnRHU2+s/id+BI=
21:55:38.227 [nioEventLoopGroup-3-6] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame opCode=1
21:55:38.228 [nioEventLoopGroup-3-6] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame length=10
/0:0:0:0:0:0:0:1:60125: helloword

21:55:38.228 [nioEventLoopGroup-3-6] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=1 length=40

总结介绍:

  • java由netty websocket 实现
  • 包括三个类一个启动类,一个初始化类,一个通道类都可以通过netty官网看介绍
  • html由websocket实现
  • netty官网https://netty.io/
  • htmlwebsocket 可以通过网络搜索获取到内部规则

ok

文字持续更新

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP