图片瀑布流网站模板,手机网站特效代码,江苏省住房城乡建设厅网站,wordpress的网站怎样添加地图坐标目录 一、简介
二、特点
三、websock应用场景
四、websocket案例
1. 服务端
2. 处理器
3. 页面端处理
五、参考文献 一、简介
没有其他技术能够像WebSocket一样提供真正的双向通信#xff0c;许多web开发者仍然是依赖于ajax的长轮询来
实现。#xff08;注#xff…目录 一、简介
二、特点
三、websock应用场景
四、websocket案例
1. 服务端
2. 处理器
3. 页面端处理
五、参考文献 一、简介
没有其他技术能够像WebSocket一样提供真正的双向通信许多web开发者仍然是依赖于ajax的长轮询来
实现。注我认为长轮询是富于创造性和多功能性的虽然这只是一个不太完美的解决办法hack
对Websocket缺少热情也许是因为多年前他的安全性的脆弱抑或者是缺少浏览器的支持不管怎样
这两个问题都已经被解决了。它的最大特点就是服务器可以主动向客户端推送信息客户端也可以主动
向服务器发送信息是真正的双向平等对话属于服务器推送技术的一种。在WebSocket API中浏览器
和服务器只需要做一个握手的动作然后浏览器和服务器之间就形成了一条快速通道。两者之间就直接
可以数据互相传送
二、特点
Websocket是应用层第七层上的一个应用层协议它必须依赖HTTP协议进行一次握手 握手成功后数
据就直接从TCP通道传输与HTTP无关了。Websocket的数据传输是frame形式传输的比如会将一条消
息分为几个frame按照先后顺序传输出去。
这样做会有几个好处
建立在 TCP 协议之上服务器端的实现比较容易。与 HTTP 协议有着良好的兼容性。默认端口也是80和443并且握手阶段采用 HTTP 协议因此握手
时不容易屏蔽能通过各种HTTP 代理服务器。
数据格式比较轻量性能开销小通信高效。可以发送文本也可以发送二进制数据。没有同源限制客户端可以与任意服务器通信。协议标识符是ws如果加密则为wss服务器网址就是 URL。大数据的传输可以分片传输不用考虑到数据大小导致的长度标志位不足够的情况。和http的chunk一样可以边生成数据边传递消息即提高传输效率。
三、websock应用场景
既然http无法满足用户的所有需求那么为之诞生的websocket必然有其诸多应用场景。
如
实时显示网站在线人数账户余额等数据的实时更新多玩家网络游戏多媒体聊天如聊天室
四、websocket案例
1. 服务端
public class WebSocketServer {public static void main(String[] args) {//创建线程组 负责接收EventLoopGroup bossGroup new NioEventLoopGroup(1);//线程组 负责读写工作线程EventLoopGroup workerGroup new NioEventLoopGroup();//创建启动类ServerBootstrap bootstrap new ServerBootstrap();//指定启动的参数bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128) //option指的是bossGroup里面的可选项.childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializerSocketChannel() {Overrideprotected void initChannel(SocketChannel ch) throws Exception {//在通道的流水线上加入一个通道处理器ch.pipeline().addLast(logging, new LoggingHandler())//设置log监听器并且日志级别为debug方便观察运行流程.addLast(http-codec, new HttpServerCodec())//设置解码器.addLast(aggregator, new HttpObjectAggregator(65536))//聚合器使用websocket会用到.addLast(http-chunked, new ChunkedWriteHandler())//用于大数据的分区传输.addLast(hanlder, new WebSocketHandler());}});System.out.println(服务器启动了);try {//启动的时候绑定端口返回ChannelFuture异步启动ChannelFuture channelFuture bootstrap.bind(8081).sync();//添加监听器channelFuture.addListener(new ChannelFutureListener() {Overridepublic void operationComplete(ChannelFuture future) throws Exception {if (future.isSuccess()) {System.out.println(端口: 8081启动成功);} else {System.out.println(端口: 8081启动失败);}}});channelFuture.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}
2. 处理器
public class WebSocketHandler extends SimpleChannelInboundHandlerObject {//设置通道组static ChannelGroup group new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);//日志对象private final Logger logger Logger.getLogger(this.getClass());//创建握手对象private WebSocketServerHandshaker handshaker;/*** 通道激活* param ctx* throws Exception*/Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {logger.debug(ctx.channel().remoteAddress()加入群聊);group.add(ctx.channel());}/*** 通道销毁* param ctx* throws Exception*/Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {logger.debug(ctx.channel().remoteAddress()退出群聊);group.add(ctx.channel());}/*** 服务器读处理* param ctx* param msg* throws Exception*/Overrideprotected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {logger.debug(收到消息);if(msg instanceof FullHttpRequest){//以http请求方式接入升级websockethandleHttpRequest(ctx, (FullHttpRequest) msg);}if(msg instanceof WebSocketFrame){//处理websocket客户端的消息handleWebSocketFrame(ctx, (WebSocketFrame) msg);}}/*** websocket处理* param ctx* param frame*/private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){Channel channel ctx.channel();if(frame instanceof CloseWebSocketFrame){handshaker.close(channel, (CloseWebSocketFrame)frame.retain());return;}if(frame instanceof PingWebSocketFrame){channel.write(new PongWebSocketFrame(frame.content().retain()));return;}if(frame instanceof TextWebSocketFrame){String text ((TextWebSocketFrame) frame).text();logger.debug(服务端收到text);TextWebSocketFrame tws new TextWebSocketFrame(ctx.channel().remoteAddress()说:text);group.writeAndFlush(tws);}else{logger.debug(不支持非文本格式);throw new UnsupportedOperationException(不支持非文本格式ctx.channel().id());}}/*** http请求处理* param ctx* param req*/private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {//如果请求解码失败或者不是websocketif(req.decoderResult().isFailure() || !websocket.equals(req.headers().get(Upgrade))){sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}//创建websocket握手工厂WebSocketServerHandshakerFactory factory new WebSocketServerHandshakerFactory(ws://localhost:8081/websocket, null, false);//创建新的握手handshaker factory.newHandshaker(req);if(handshaker null){//不支持WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());}else{//握手handshaker.handshake(ctx.channel(), req);}}//发送响应private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse resp){//如果响应码不是200if(resp.status().code() ! 200){//创建错误状态码数据ByteBuf buf Unpooled.copiedBuffer(resp.status().toString(), CharsetUtil.UTF_8);resp.content().writeBytes(buf);buf.release();}//回写状态码ChannelFuture channelFuture ctx.channel().writeAndFlush(resp);if(!HttpUtil.isKeepAlive(req) || resp.status().code() ! 200){channelFuture.addListener(ChannelFutureListener.CLOSE);}}}
3. 页面端处理
!DOCTYPE html
html langen
headmeta charsetUTF-8titleTitle/title
/head
body
scriptvar socket;//判断当前浏览器是否支持websocketif(window.WebSocket) {//go onsocket new WebSocket(ws://localhost:7000/hello2);//相当于channelReado, ev 收到服务器端回送的消息socket.onmessage function (ev) {var rt document.getElementById(responseText);rt.value rt.value \n ev.data;}//相当于连接开启(感知到连接开启)socket.onopen function (ev) {var rt document.getElementById(responseText);rt.value 连接开启了..}//相当于连接关闭(感知到连接关闭)socket.onclose function (ev) {var rt document.getElementById(responseText);rt.value rt.value \n 连接关闭了..}} else {alert(当前浏览器不支持websocket)}//发送消息到服务器function send(message) {if(!window.socket) { //先判断socket是否创建好return;}if(socket.readyState WebSocket.OPEN) {//通过socket 发送消息socket.send(message)} else {alert(连接没有开启);}}
/scriptform onsubmitreturn falsetextarea namemessage styleheight: 300px; width: 300px/textareainput typebutton value发生消息 onclicksend(this.form.message.value)textarea idresponseText styleheight: 300px; width: 300px/textareainput typebutton value清空内容 onclickdocument.getElementById(responseText).value/form
/body
/html
五、参考文献
HTML5 WebSocket