WebSocket长连接

一、创建服务端代码

1、MyServer 类

public class MyServer {
public static void main(String[] args) throws Exception{
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(new InetSocketAddress(8899)).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}

  

2、WebSocketChannelInitializer 类

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel>{

    protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandle());
}
}

  

3、TextWebSocketFrameHandle 类

public class TextWebSocketFrameHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
CommonUtil.println("收到消息:" + msg.text());
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now()));
} @Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
CommonUtil.println("handlerAdded:" +ctx.channel().id().asLongText());
} @Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
CommonUtil.println("handlerRemoved:" +ctx.channel().id().asLongText());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
CommonUtil.println("异常发生");
ctx.close();
}
}

  

二、编写客户端WebSocket代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<script type="text/javascript"> var socket; if(window.WebSocket){
socket = new WebSocket("ws://localhost:8899/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 + "\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 name="message" style="width: 400px ; height: 200px;" ></textarea> <input type="button" value="发送数据" onclick="send(this.form.message.value)"> <h3>服务端输出:</h3> <textarea id="responseText" style="width: 400px ; height: 300px;" ></textarea> <input type="button" value="清空内容" onclick="javascript: document.getElementById('responseText').value=''">
</form>
</body>
</html>

  

三、测试

1、启动服务端

2、打开页面 http://localhost:7080/test.html

可以看到,连接开启。

服务端输出如下图:

四、进入页面的开发者模式

可以发现,

1、Status Code:101 Switching Protocols。 原来是Http的,切换成Socket

2、请求头: Upgrade:websocket

虽然请求发送的ws,但是要先发送的http请求建立连接,连接建立好后,将http升级到websockent协议上

五、测试发送消息

整个请求建立在webSocket协议之上。

六、连接关闭

当服务端停掉后,可以收到连接关闭。

七、websocket的请求和接收

如下图: Hello是请求, 服务器时间是接收

最新文章

  1. .NET Core中的认证管理解析
  2. Spring JPA Junit 关闭自动回滚
  3. Linux Red hat修改主机名
  4. VC++的菜单控制和自绘菜单
  5. HDU Sky数 2097
  6. 1065: [NOI2008]奥运物流 - BZOJ
  7. 每天一个JavaScript实例-从一个div元素删除一个段落
  8. iOS的触摸事件
  9. python屏幕的交互(读取输出信息)input,raw_input的区别
  10. Flink流处理的时间窗口
  11. [LeetCode] 8. 字符串转换整数 (atoi)
  12. java 工厂模式 转载
  13. canal 配置 详细说明
  14. table滑块
  15. Astah Professional安装
  16. Spring Data Redis —— 快速入门
  17. require.js初试(with angular &amp; optimization)
  18. ubuntu14.04安装opengl
  19. JpGraph使用详解
  20. 【python】Beautiful Soup的使用

热门文章

  1. Nginx 常用命令并实现最基本的反向代理
  2. Gitlab配置webhooks实现自动化部署
  3. Github强制找回管理员账号密码
  4. 【兼容调试】cffi library &#39;_openssl&#39; has no function, constant or global variable named &#39;Cryptography_HAS
  5. package-lock.json的作用(转载)
  6. springboot2.1.3+jacoco检测代码覆盖率
  7. 命令启用Windows7 .NetFramework 3.5
  8. 用session防止网站页面被频繁刷新
  9. VUE--404页面
  10. SQLAlchemy的应用创建