本文参考《Netty权威指南》
├── WebSocketServerHandler.java
├── WebSocketServer.java
└── wsclient.html
package com.xh.netty.test11;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler; /**
* Created by root on 1/8/18.
*/
public class WebSocketServer {
public void run(int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("http-codec", new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("http-chunked", new ChunkedWriteHandler());
pipeline.addLast("handler", new WebSocketServerHandler());
}
});
Channel ch = b.bind(port).sync().channel();
System.out.println("websocketserver start port at " + port);
ch.closeFuture().sync(); } catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} public static void main(String[] args) {
int port = 8080;
if (args.length > 0) {
port = Integer.valueOf(args[0]); }
new WebSocketServer().run(port); }
}
package com.xh.netty.test11;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil; import java.util.Date;
import java.util.logging.Logger; import static io.netty.handler.codec.http.HttpHeaderUtil.isKeepAlive;
import static io.netty.handler.codec.http.HttpHeaderUtil.setContentLength; /**
* Created by root on 1/8/18.
*/
public class WebSocketServerHandler extends SimpleChannelInboundHandler {
private WebSocketServerHandshaker handshaker; @Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg.toString());
//http
if (msg instanceof FullHttpRequest) {
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {//websocket
handleWebsocketFrame(ctx, (WebSocketFrame) msg);
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} private void handleWebsocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) {
//关闭链路指令
if (msg instanceof CloseWebSocketFrame) {
handshaker.close(ctx.channel(), (CloseWebSocketFrame) msg.retain());
return;
} //PING 消息
if (msg instanceof PingWebSocketFrame) {
ctx.write(new PongWebSocketFrame(msg.content().retain()));
return;
} //非文本
if (!(msg instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format("%s frame type not support", msg.getClass().getName())); } //应答消息
String requset = ((TextWebSocketFrame) msg).text();
ctx.channel().write(new TextWebSocketFrame(requset + " >>>>Now is " + new Date().toString())); } private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest msg) { //HTTP 请异常
if (!msg.decoderResult().isSuccess() || !"websocket".equals(msg.headers().get("Upgrade"))) {
System.out.println(msg.decoderResult().isSuccess());
System.out.println(msg.headers().get("Upgrade"));
sendHttpResponse(ctx, msg, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
} //握手
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:8080/websocket", null, false);
handshaker = wsFactory.newHandshaker(msg);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else {
handshaker.handshake(ctx.channel(), msg);
}
} private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest msg, FullHttpResponse resp) { //响应
if (resp.status().code() != 200) {
ByteBuf buf = Unpooled.copiedBuffer(resp.status().toString(), CharsetUtil.UTF_8);
resp.content().writeBytes(buf);
buf.release();
setContentLength(resp, resp.content().readableBytes());
} //非Keep-Alive,关闭链接
ChannelFuture future = ctx.channel().writeAndFlush(resp);
if (!isKeepAlive(resp) || resp.status().code() != 200) {
future.addListener(ChannelFutureListener.CLOSE);
} } }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form onsubmit="return false;">
<input type="text" name="msg" value="NETTY">
<button onclick="send(this.form.msg.value)">send</button>
<br>
<textarea id="resText"> </textarea> </form>
</body>
<script>
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
socket = new WebSocket("ws://127.0.0.1:8080/websocket");
socket.onmessage = function (event) {
var ta = document.getElementById("resText");
ta.value = "";
ta.value = event.data; }; socket.onopen = function (event) {
alert("浏览器支持WebSocket");
var ta = document.getElementById("resText");
ta.value = "";
ta.value = "浏览器支持WebSocket";
}; socket.onclose = function (event) {
var ta = document.getElementById("resText");
ta.value = "";
ta.value = "关闭WebSocket";
}
} else { alert("浏览器不支持WebSocket");
} function send(msg) {
if (!window.WebSocket) {
return; }
if (socket.readyState == WebSocket.OPEN) {
socket.send(msg);
} else {
alert("建立连接失败")
}
}
</script>
</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. (大数 string easy。。。)P1781 宇宙总统 洛谷

    题目背景 宇宙总统竞选 题目描述 地球历公元6036年,全宇宙准备竞选一个最贤能的人当总统,共有n个非凡拔尖的人竞选总统,现在票数已经统计完毕,请你算出谁能够当上总统. 输入输出格式 输入格式: pr ...

  2. lucene的普通搜索(二)

    首先得到索引: package com.wp.util; import java.io.File; import java.io.FileReader; import java.nio.file.Pa ...

  3. Win7下mysql的安装

    一.简述 mysql与oracle相比小,便宜,装机量大,下载地址:https://www.mysql.com/downloads/,去找Community Edition,然后根据自己的Window ...

  4. 【.net】未能加载文件或程序集“System.Web.Mvc, Version=5.2.2.0

    #车祸现场 未能加载文件或程序集“System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或 ...

  5. List数组

    大家好,我是蜀云泉.我的博文之中存在的不足之处希望大家包涵. 今天学习unity时,在实现某个功能的脚本中发现了List数组.关于List数组的问题我在学C#时已经接触了一点,但是我比较粗心和浮躁以前 ...

  6. JAVA核心技术I---JAVA基础知识(不可变对象和字符串)

    一:不可变对象 不可变对象(Immutable Object) –一旦创建,这个对象(状态/值)不能被更改了–其内在的成员变量的值就不能修改了. –典型的不可变对象 • 八个基本型别的包装类的对象 • ...

  7. WEBGIS网页崩溃问题分析

    加载某一地区的系统页面时,过了几十秒,页面空白.曾经捕获到是WMTS服务异常的问题.本人推测可能是底图服务停止,使得WMTS服务无法进行而抛出的异常. 为了证实自己的猜想,鄙人对一个正常的系统,修改为 ...

  8. 关闭Android ActionBar

    修改Styles.xml中 <resources> <!-- Base application theme. --> <style name="AppTheme ...

  9. ASP.NET Web API 2 之文件下载

    Ø  前言 目前 ASP.NET Web API 的应用非常广泛,主要承载着服务端与客户端的数据传输与处理,如果需要使用 Web API 实现文件下载,该 实现呢,其实也是比较简单,以下示例用于下载安 ...

  10. Weex Ui - Weex Conf 2018 干货分享

    本文是2018年 Weex Conf 中议题<Weex + Ui>的内容文档整理,主要给大家介绍飞猪 Weex 技术体系从无到有的过程,包括 Weex Ui 组件库的开发和发展,重点分享在 ...