加入收藏 | 设为首页 | 会员中心 | 我要投稿 航空爱好网 (https://www.52kongjun.com/)- 自然语言处理、云硬盘、数据治理、数据工坊、存储容灾!
当前位置: 首页 > 教程 > 正文

Netty4之简单创建WebSocket服务

发布时间:2023-11-01 11:00:51 所属栏目:教程 来源:互联网
导读:   websocket.server.RandomResponseGenerator.java



  package websocket.server;



  import io.netty.channel.ChannelHandlerContext;



  import io.netty.handle
  websocket.server.RandomResponseGenerator.java
 
  package websocket.server;
 
  import io.netty.channel.ChannelHandlerContext;
 
  import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
 
  import java.util.Random;
 
  import org.apache.log4j.Logger;
 
  public class RandomResponseGenerator extends Thread{
 
   private ChannelHandlerContext ctx;
    
   private Random random = new Random();
 
   private int messageCount = 10;
 
   public RandomResponseGenerator(ChannelHandlerContext ctx){
 
   this.ctx=ctx;
 
   }
 
   private Logger logger = Logger.getLogger(RandomResponseGenerator.class);
 
   public void run() {
 
   while(messageCount-->0){
 
   ctx.writeAndFlush(new TextWebSocketFrame("[server] the random value is : "+random.nextInt(20)));
 
   try {
 
   Thread.sleep(1000);
 
   } catch (InterruptedException e) {
 
   logger.error("encounter an exception",e);
 
   }
 
   }
 
   }
 
  }
 
  复制代码
 
  websocket.server.HttpRequestHandler.java
 
  package websocket.server;
 
  import io.netty.channel.ChannelHandlerContext;
 
  import io.netty.channel.SimpleChannelInboundHandler;
 
  import io.netty.handler.codec.http.FullHttpRequest;
 
  import org.apache.log4j.Logger;
 
  public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
 
      private final String wsUri;

      public HttpRequestHandler(String wsUri) {
 
          this.wsUri = wsUri;
 
      }
 
      private Logger logger = Logger.getLogger(HttpRequestHandler.class);      
 
      @Override
 
      protected void channelRead0(final ChannelHandlerContext ctx, FullHttpRequest msg)
 
              throws Exception {
 
          if(wsUri.equalsIgnoreCase(msg.getUri())){
 
           logger.info("a websocket connection established ... ");
 
           logger.info("the request uri is : "+msg.getUri());
 
           new RandomResponseGenerator(ctx).start();
 
              ctx.fireChannelRead(msg.retain());
 
          }
 
      }
 
  }
 
  复制代码
 
  websocket.server.TextWebSocketFrameHandler.java
 
  package websocket.server;
 
  import io.netty.channel.ChannelHandlerContext;
 
  import io.netty.channel.SimpleChannelInboundHandler;
 
  import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
 
  import org.apache.log4j.Logger;
 
  public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
 
      private Logger logger = Logger.getLogger(TextWebSocketFrameHandler.class);
 
      @Override
 
      protected void channelRead0(ChannelHandlerContext ctx,
 
              TextWebSocketFrame msg) throws Exception {
 
       String message = msg.content().toString(io.netty.util.CharsetUtil.UTF_8);
 
       logger.info("receive below information from client:\n"+message);
 
       ctx.writeAndFlush(new TextWebSocketFrame("[server] receive message ["+message+"] successfully"));
 
      }
 
  }
 
  复制代码
 
  websocket.server.WebSocketServerInitializer.java
 
  package websocket.server;
 
  import io.netty.channel.Channel;
 
  import io.netty.channel.ChannelInitializer;
 
  import io.netty.channel.ChannelPipeline;
 
  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<Channel> {
 
      @Override
 
      protected void initChannel(Channel ch) throws Exception {
 
          ChannelPipeline pipeline = ch.pipeline();
 
          pipeline.addLast(new HttpServerCodec());
 
          pipeline.addLast(new ChunkedWriteHandler());
 
          pipeline.addLast(new HttpObjectAggregator(64*1024));
 
          pipeline.addLast(new HttpRequestHandler("/ws"));           
 
          pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
 
          pipeline.addLast(new TextWebSocketFrameHandler());

      }
 
  }
 
  复制代码
 
  pom.xml
 
   <dependencies>
 
   <dependency>
 
   <groupId>log4j</groupId>
 
   <artifactId>log4j</artifactId>
 
   <version>1.2.14</version>
 
   </dependency>
 
   <dependency>
 
   <groupId>commons-logging</groupId>
 
   <artifactId>commons-logging</artifactId>
 
   <version>1.1.1</version>
 
   </dependency>
 
   <dependency>
 
   <groupId>io.netty</groupId>
 
   <artifactId>netty-all</artifactId>
 
   <version>4.0.29.Final</version>
 
   </dependency>
 
   </dependencies>
 
  复制代码
 
  使用HTML5作为websocket前端实现
 
  index.html
 
  <!DOCTYPE html>
 
  <html>
 
  <head>
 
  <meta charset="UTF-8">
 
  <title>Insert title here</title>
 
  </head>
 
  <body>
 
      <script type="text/javascript">
 
          var socket;
 
          if (!window.WebSocket) {
 
              window.WebSocket = window.MozWebSocket;
 
          }
 
          if (window.WebSocket) {
 
              socket = new WebSocket("ws://localhost:8844/ws");
 
              socket.onmessage = function(event) {
 
                  var ta = document.getElementById('responseText');
 
                  ta.value = ta.value + '\n' + event.data
 
              };
 
              socket.onopen = function(event) {
 
                  var ta = document.getElementById('responseText');
 
                  ta.value = "连接开启!";
 
              };
 
              socket.onclose = function(event) {
 
                  var ta = document.getElementById('responseText');
 
                  ta.value = ta.value + "连接被关闭";
 
              };
 
          } else {
 
              alert("你的浏览器不支持!");
 
          }
 
          function send(message) {
 
              if (!window.WebSocket) {
 
                  return;
 
              }
 
              if (socket.readyState == WebSocket.OPEN) {
 
                  socket.send(message);
 
              } else {
 
                  alert("连接没有开启.");
 
              }
 
          }
 
      </script>
 
      <form onsubmit="return false;">
 
          <input type="text" name="message" value="Hello, World!"><input
 
              type="button" value="发送消息"
 
              onclick="send(this.form.message.value)">
 
          <h4>输出:</h4>
 
          <textarea id="responseText" ></textarea>
 
          <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空">
 
      </form>
 
  </body>
 
  </html>
 

(编辑:航空爱好网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章