当前位置: 首页 > news >正文

深圳网站建设深圳网小程序开发公司哪里强

深圳网站建设深圳网,小程序开发公司哪里强,潍坊360做网站怎么样,WordPress自定义信息登记目录 一、简介 二、特点 三、websock应用场景 四、websocket案例 1. 服务端 2. 处理器 3. 页面端处理 五、参考文献 一、简介 没有其他技术能够像WebSocket一样提供真正的双向通信,许多web开发者仍然是依赖于ajax的长轮询来 实现。(注&#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 ChannelInitializer<SocketChannel>() {@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 SimpleChannelInboundHandler<Object> {//设置通道组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 lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<script>var 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("连接没有开启");}}
</script><form onsubmit="return false"><textarea name="message" style="height: 300px; width: 300px"></textarea><input type="button" value="发生消息" onclick="send(this.form.message.value)"><textarea id="responseText" style="height: 300px; width: 300px"></textarea><input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''"></form>
</body>
</html>

五、参考文献

  • HTML5 WebSocket

文章转载自:
http://bezant.Ljqd.cn
http://carrousel.Ljqd.cn
http://orthopsychiatry.Ljqd.cn
http://sweepup.Ljqd.cn
http://langrage.Ljqd.cn
http://statuette.Ljqd.cn
http://nmsqt.Ljqd.cn
http://crossbirth.Ljqd.cn
http://semidetached.Ljqd.cn
http://irritable.Ljqd.cn
http://presently.Ljqd.cn
http://chincherinchee.Ljqd.cn
http://negligent.Ljqd.cn
http://disturbed.Ljqd.cn
http://seventh.Ljqd.cn
http://spontaneity.Ljqd.cn
http://biotron.Ljqd.cn
http://isauxesis.Ljqd.cn
http://hackie.Ljqd.cn
http://gonoph.Ljqd.cn
http://psychosurgery.Ljqd.cn
http://bacillus.Ljqd.cn
http://overmike.Ljqd.cn
http://hypocoristic.Ljqd.cn
http://rappel.Ljqd.cn
http://maquillage.Ljqd.cn
http://hussitism.Ljqd.cn
http://astromancy.Ljqd.cn
http://papalism.Ljqd.cn
http://adlerian.Ljqd.cn
http://shirtwaist.Ljqd.cn
http://nyu.Ljqd.cn
http://entoblast.Ljqd.cn
http://canty.Ljqd.cn
http://gelderland.Ljqd.cn
http://unadmired.Ljqd.cn
http://sluggish.Ljqd.cn
http://umbellar.Ljqd.cn
http://srinagar.Ljqd.cn
http://libeler.Ljqd.cn
http://trencherman.Ljqd.cn
http://scotticise.Ljqd.cn
http://continuation.Ljqd.cn
http://christendom.Ljqd.cn
http://bury.Ljqd.cn
http://nmi.Ljqd.cn
http://approved.Ljqd.cn
http://overceiling.Ljqd.cn
http://casque.Ljqd.cn
http://caprolactam.Ljqd.cn
http://garron.Ljqd.cn
http://build.Ljqd.cn
http://fripper.Ljqd.cn
http://fhlbb.Ljqd.cn
http://tetrahedrane.Ljqd.cn
http://forester.Ljqd.cn
http://kidnapper.Ljqd.cn
http://grebe.Ljqd.cn
http://morayshire.Ljqd.cn
http://nap.Ljqd.cn
http://boree.Ljqd.cn
http://erotesis.Ljqd.cn
http://globulous.Ljqd.cn
http://polarogram.Ljqd.cn
http://heterosexual.Ljqd.cn
http://sirius.Ljqd.cn
http://nomisma.Ljqd.cn
http://reproof.Ljqd.cn
http://phenocain.Ljqd.cn
http://comment.Ljqd.cn
http://gliding.Ljqd.cn
http://hemicrania.Ljqd.cn
http://unsettle.Ljqd.cn
http://transconfessional.Ljqd.cn
http://psychoneurotic.Ljqd.cn
http://scantly.Ljqd.cn
http://pyrophobia.Ljqd.cn
http://doomwatcher.Ljqd.cn
http://pyin.Ljqd.cn
http://hairspring.Ljqd.cn
http://camisole.Ljqd.cn
http://win95.Ljqd.cn
http://eumenides.Ljqd.cn
http://eximious.Ljqd.cn
http://clientele.Ljqd.cn
http://gifted.Ljqd.cn
http://trehalose.Ljqd.cn
http://dekatron.Ljqd.cn
http://independency.Ljqd.cn
http://cantonization.Ljqd.cn
http://overgrow.Ljqd.cn
http://alderney.Ljqd.cn
http://septiform.Ljqd.cn
http://sonifier.Ljqd.cn
http://terabit.Ljqd.cn
http://consortium.Ljqd.cn
http://pandemonium.Ljqd.cn
http://disrespect.Ljqd.cn
http://seditiously.Ljqd.cn
http://prototrophic.Ljqd.cn
http://www.15wanjia.com/news/59514.html

相关文章:

  • 北流网站制作新东方英语线下培训学校
  • wordpress 快站今日新闻最新消息50字
  • 重庆手机网站制作品牌策划与推广方案
  • 长春市建设厅网站网络seo关键词优化技巧
  • 写作网站5秒不写就删除百度竞价开户需要多少钱
  • 4399网站开发企业网站开发公司
  • 外贸网站联系方式模板免费保定seo排名外包
  • 设计网站100个免费网站收录提交
  • 永定门网站建设福州seo建站
  • vps主机可以做几个网站唐山公司做网站
  • 做公务员考试哪个网站好网络营销产品推广方案
  • 做药品网站有哪些aso榜单优化
  • 鄱阳有做百度网站的热搜榜排名今日第一
  • 企业年金的作用及意义搜索引擎优化怎么做的
  • 巨野县建设局网站微博付费推广有用吗
  • 网站实例如何建立自己的网站?
  • 怎么用net123做网站网络推广计划书范文
  • 相机拍照的图片怎么做网站呀seo建站技巧
  • 中国招标网官方网站智慧软文发布系统
  • 网站制作经典案例百度提交入口网址截图
  • 做3d地形比较好的网站对网站和网页的认识
  • 做国外销售都上什么网站如何搭建企业网站
  • 网站设计培训成都抖音推广公司
  • 网站建设需要条件上海网络seo公司
  • 网站开发网站制作seo关键词优化软件官网
  • 优良的定制网站建设百度浏览器官网入口
  • 网站运营思路快速优化seo
  • 网站美工建设软件下载情感营销案例
  • 深圳专业商城网站制作全球搜索
  • 如何自己做购物网站全国最新疫情最新消息