1. 本文参考《Netty权威指南》
    ├── WebSocketServerHandler.java
    ├── WebSocketServer.java
    └── wsclient.html
  1. package com.xh.netty.test11;
  2.  
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.Channel;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelPipeline;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;
  11. import io.netty.handler.codec.http.HttpObjectAggregator;
  12. import io.netty.handler.codec.http.HttpServerCodec;
  13. import io.netty.handler.stream.ChunkedWriteHandler;
  14.  
  15. /**
  16. * Created by root on 1/8/18.
  17. */
  18. public class WebSocketServer {
  19. public void run(int port) {
  20. EventLoopGroup bossGroup = new NioEventLoopGroup();
  21. EventLoopGroup workerGroup = new NioEventLoopGroup();
  22. try {
  23. ServerBootstrap b = new ServerBootstrap();
  24. b.group(bossGroup, workerGroup)
  25. .channel(NioServerSocketChannel.class)
  26. .childHandler(new ChannelInitializer<SocketChannel>() {
  27. protected void initChannel(SocketChannel socketChannel) throws Exception {
  28. ChannelPipeline pipeline = socketChannel.pipeline();
  29. pipeline.addLast("http-codec", new HttpServerCodec());
  30. pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
  31. pipeline.addLast("http-chunked", new ChunkedWriteHandler());
  32. pipeline.addLast("handler", new WebSocketServerHandler());
  33. }
  34. });
  35. Channel ch = b.bind(port).sync().channel();
  36. System.out.println("websocketserver start port at " + port);
  37. ch.closeFuture().sync();
  38.  
  39. } catch (InterruptedException e) {
  40. e.printStackTrace();
  41. } finally {
  42. bossGroup.shutdownGracefully();
  43. workerGroup.shutdownGracefully();
  44. }
  45. }
  46.  
  47. public static void main(String[] args) {
  48. int port = 8080;
  49. if (args.length > 0) {
  50. port = Integer.valueOf(args[0]);
  51.  
  52. }
  53. new WebSocketServer().run(port);
  54.  
  55. }
  56. }
  1. package com.xh.netty.test11;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelFuture;
  6. import io.netty.channel.ChannelFutureListener;
  7. import io.netty.channel.ChannelHandlerContext;
  8. import io.netty.channel.SimpleChannelInboundHandler;
  9. import io.netty.handler.codec.http.*;
  10. import io.netty.handler.codec.http.websocketx.*;
  11. import io.netty.util.CharsetUtil;
  12.  
  13. import java.util.Date;
  14. import java.util.logging.Logger;
  15.  
  16. import static io.netty.handler.codec.http.HttpHeaderUtil.isKeepAlive;
  17. import static io.netty.handler.codec.http.HttpHeaderUtil.setContentLength;
  18.  
  19. /**
  20. * Created by root on 1/8/18.
  21. */
  22. public class WebSocketServerHandler extends SimpleChannelInboundHandler {
  23. private WebSocketServerHandshaker handshaker;
  24.  
  25. @Override
  26. protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
  27. System.out.println(msg.toString());
  28. //http
  29. if (msg instanceof FullHttpRequest) {
  30. handleHttpRequest(ctx, (FullHttpRequest) msg);
  31. } else if (msg instanceof WebSocketFrame) {//websocket
  32. handleWebsocketFrame(ctx, (WebSocketFrame) msg);
  33. }
  34. }
  35.  
  36. @Override
  37. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  38. ctx.flush();
  39. }
  40.  
  41. @Override
  42. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  43. cause.printStackTrace();
  44. ctx.close();
  45. }
  46.  
  47. private void handleWebsocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) {
  48. //关闭链路指令
  49. if (msg instanceof CloseWebSocketFrame) {
  50. handshaker.close(ctx.channel(), (CloseWebSocketFrame) msg.retain());
  51. return;
  52. }
  53.  
  54. //PING 消息
  55. if (msg instanceof PingWebSocketFrame) {
  56. ctx.write(new PongWebSocketFrame(msg.content().retain()));
  57. return;
  58. }
  59.  
  60. //非文本
  61. if (!(msg instanceof TextWebSocketFrame)) {
  62. throw new UnsupportedOperationException(String.format("%s frame type not support", msg.getClass().getName()));
  63.  
  64. }
  65.  
  66. //应答消息
  67. String requset = ((TextWebSocketFrame) msg).text();
  68. ctx.channel().write(new TextWebSocketFrame(requset + " >>>>Now is " + new Date().toString()));
  69.  
  70. }
  71.  
  72. private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest msg) {
  73.  
  74. //HTTP 请异常
  75. if (!msg.decoderResult().isSuccess() || !"websocket".equals(msg.headers().get("Upgrade"))) {
  76. System.out.println(msg.decoderResult().isSuccess());
  77. System.out.println(msg.headers().get("Upgrade"));
  78. sendHttpResponse(ctx, msg, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
  79. return;
  80. }
  81.  
  82. //握手
  83. WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:8080/websocket", null, false);
  84. handshaker = wsFactory.newHandshaker(msg);
  85. if (handshaker == null) {
  86. WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
  87.  
  88. } else {
  89. handshaker.handshake(ctx.channel(), msg);
  90. }
  91. }
  92.  
  93. private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest msg, FullHttpResponse resp) {
  94.  
  95. //响应
  96. if (resp.status().code() != 200) {
  97. ByteBuf buf = Unpooled.copiedBuffer(resp.status().toString(), CharsetUtil.UTF_8);
  98. resp.content().writeBytes(buf);
  99. buf.release();
  100. setContentLength(resp, resp.content().readableBytes());
  101. }
  102.  
  103. //非Keep-Alive,关闭链接
  104. ChannelFuture future = ctx.channel().writeAndFlush(resp);
  105. if (!isKeepAlive(resp) || resp.status().code() != 200) {
  106. future.addListener(ChannelFutureListener.CLOSE);
  107. }
  108.  
  109. }
  110.  
  111. }
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <form onsubmit="return false;">
  9. <input type="text" name="msg" value="NETTY">
  10. <button onclick="send(this.form.msg.value)">send</button>
  11. <br>
  12. <textarea id="resText">
  13.  
  14. </textarea>
  15.  
  16. </form>
  17. </body>
  18. <script>
  19. var socket;
  20. if (!window.WebSocket) {
  21. window.WebSocket = window.MozWebSocket;
  22. }
  23. if (window.WebSocket) {
  24. socket = new WebSocket("ws://127.0.0.1:8080/websocket");
  25. socket.onmessage = function (event) {
  26. var ta = document.getElementById("resText");
  27. ta.value = "";
  28. ta.value = event.data;
  29.  
  30. };
  31.  
  32. socket.onopen = function (event) {
  33. alert("浏览器支持WebSocket");
  34. var ta = document.getElementById("resText");
  35. ta.value = "";
  36. ta.value = "浏览器支持WebSocket";
  37. };
  38.  
  39. socket.onclose = function (event) {
  40. var ta = document.getElementById("resText");
  41. ta.value = "";
  42. ta.value = "关闭WebSocket";
  43. }
  44. } else {
  45.  
  46. alert("浏览器不支持WebSocket");
  47. }
  48.  
  49. function send(msg) {
  50. if (!window.WebSocket) {
  51. return;
  52.  
  53. }
  54. if (socket.readyState == WebSocket.OPEN) {
  55. socket.send(msg);
  56. } else {
  57. alert("建立连接失败")
  58. }
  59. }
  60. </script>
  61. </html>

Netty实现简单WebSocket服务器的更多相关文章

  1. 一款基于Netty开发的WebSocket服务器

    代码地址如下:http://www.demodashi.com/demo/13577.html 一款基于Netty开发的WebSocket服务器 这是一款基于Netty框架开发的服务端,通信协议为We ...

  2. Swoole学习(五)Swoole之简单WebSocket服务器的创建

    环境:Centos6.4,PHP环境:PHP7 服务端代码 <?php //创建websocket服务器 $host = '0.0.0.0'; $port = ; $ws = new swool ...

  3. Netty实现简单HTTP服务器

    netty package com.dxz.nettydemo.http; import java.io.UnsupportedEncodingException; import io.netty.b ...

  4. (二)基于Netty的高性能Websocket服务器(netty-websocket-spring-boot)

    @toc Netty是一款基于NIO(Nonblocking I/O,非阻塞IO)开发的网络通信框架,对比于BIO(Blocking I/O,阻塞IO),他的并发性能得到了很大提高. 1.Netty为 ...

  5. Netty实现简单UDP服务器

    本文参考<Netty权威指南> 文件列表: ├── ChineseProverbClientHandler.java ├── ChineseProverbClient.java ├── C ...

  6. netty中的websocket

    使用WebSocket 协议来实现一个基于浏览器的聊天室应用程序,图12-1 说明了该应用程序的逻辑: (1)客户端发送一个消息:(2)该消息将被广播到所有其他连接的客户端. WebSocket 在从 ...

  7. netty系列之:使用netty搭建websocket服务器

    目录 简介 netty中的websocket websocket的版本 FrameDecoder和FrameEncoder WebSocketServerHandshaker WebSocketFra ...

  8. 【Netty】(7)---搭建websocket服务器

    [Netty](7)---搭建websocket服务器 说明:本篇博客是基于学习某网有关视频教学. 目的:创建一个websocket服务器,获取客户端传来的数据,同时向客户端发送数据 一.服务端 1. ...

  9. netty的简单的应用例子

    一.简单的聊天室程序 public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...

随机推荐

  1. pt-kill 用法记录

    pt-kill 用法记录 # 参考资料Percona-Toolkit系列之pt-kill杀会话利器http://www.fordba.com/percona-toolkit-pt-kill.html ...

  2. springMVC的参数检验

    先说应用场景,比如说前台传来一个参数,我们肯定得在后台判断一下,比如id不能为空了,电话号码不能少于11位了等等.如果在service层一个一个判断岂不是要累死个人.代码也不简洁,这时候我们肯定会想到 ...

  3. 15. 迭代器模式(Iterator Pattern)

    动机(Motivate):     在软件构建过程中,集合对象内部结构常常变化各异.但对于这些集合对象,我们希望在不暴露其内部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历 ...

  4. Maccms8.x 命令执行漏洞分析

    下载链接https://share.weiyun.com/23802397ed25681ad45c112bf34cc6db 首先打开Index.php $m = be('get','m'); m参数获 ...

  5. 原生JavaScript运动功能系列(四):多物体多值链式运动

    原生JavaScript运动功能系列(一):运动功能剖析与匀速运动实现 原生JavaScript运动功能系列(二):缓冲运动 原生JavaScript运动功能系列(三):多物体多值运动 多物体多值链式 ...

  6. elasticsearch 通过HTTP RESTful API 操作数据

    1.索引样例数据 下载样例数据集链接 下载后解压到ES的bin目录,然后加载到elasticsearch集群 curl -XPOST 127.0.0.1:9200/bank/account/_bulk ...

  7. HDU 1027(数字排列 STL)

    题意是求 n 个数在全排列中的第 m 个序列. 直接用 stl 中的 next_permutation(a, a+n) (这个函数是求一段序列的下一个序列的) 代码如下: #include <b ...

  8. ArcGis 拓扑检查——狭长角锐角代码C#

    中学的时候醉心于研究怎么“逃课”,大学的时候豁然开悟——最牛逼的逃课是准时准地儿去上每一课,却不知到老师讲的啥,“大隐隐于市”大概就是这境界吧. 用到才听说有“余弦定理”这么一个东西,遂感叹“白上了大 ...

  9. 解决 Android Device Monitor 常见问题

    Ø  简介 什么是 Android Device Monitor,中文意思就是安卓设备监视器,用于管理安装设备(手机.模拟器)用的.下面列出 Android Device Monitor 常见的一些问 ...

  10. 高并发秒杀系统--mybatis整合技巧

    mybatis实现DAO接口编码技巧 1.XML文件通过namespace命名空间关联接口类 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD ...