分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

html5 WebSocket

发布时间:2023-09-06 01:40责任编辑:彭小芳关键词:Web

websoket 是html5 提供的单个 TCP 连接上进行全双工通讯的协议。

创建websoket对象

var Socket = new WebSocket(url, [protocol] );

其中url是必填项,指定的url 。第二个参数protocol是可选项,可以不填,指可接受的子协议。

例子:

if ("WebSocket" in window) ???????????{ ??????????????alert("您的浏览器支持 WebSocket!"); ?????????????????????????????// 打开一个 web socket ??????????????var ws = new WebSocket("ws://localhost:9998/echo"); ??????????????????????????????ws.onopen = function() ??????????????{ ?????????????????// Web Socket 已连接上,使用 send() 方法发送数据 ?????????????????ws.send("发送数据"); ?????????????????alert("数据发送中..."); ??????????????}; ??????????????????????????????ws.onmessage = function (evt) ???????????????{ ??????????????????var received_msg = evt.data; ?????????????????alert("数据已接收..."); ??????????????}; ??????????????????????????????ws.onclose = function() ??????????????{ ??????????????????// 关闭 websocket ?????????????????alert("连接已关闭..."); ???????????????}; ???????????} ???????????????????????else ???????????{ ??????????????// 浏览器不支持 WebSocket ??????????????alert("您的浏览器不支持 WebSocket!"); ???????????}

实例:

(function() { ???????????var socket = new WebSocket(‘ws://1994‘); ????????????????????????var shock = document.getElementById(‘shock‘); ???????????var mar_bom0 = document.getElementById(‘mar_bom0‘); ???????????var mar_bom1 = document.getElementById(‘mar_bom1‘); ???????????var mar_bom2 = document.getElementById(‘mar_bom2‘); ???????????var end = document.getElementById(‘end‘); ???????????var suspend = document.getElementById(‘suspend‘); ???????????var continue1 = document.getElementById(‘continue‘); ???????????socket.onopen = function(event) { ???????????????layer.msg(‘座椅连接成功!‘); ???????????????var content = ‘5 ‘; ???????????????// var content = ‘58 46 5a ‘+‘<?php echo $arr[‘position‘]; ?>‘+‘ 00 05 01 ‘+‘<?php echo $arr[‘mac‘]; ?>‘+‘ 00 00 00 00 00 00 00 00 00 00 00 00 FF FF 45 4e 44‘; ???????????????if(content.length <= 0) { ???????????????????layer.msg(‘指令为空!‘); ???????????????????return false; ???????????????} ???????????????socket.send(content); ???????????????$("#img0").attr(‘src‘,‘__STATIC__/theme/default/img/car/start.png‘); ???????????????console.log(content); ???????????} ???????????/** ????????????* 接受服务端传送的数据 ????????????*/ ???????????socket.onmessage = function(event) { ???????????????console.log(event.data); ???????????} ???????????socket.onerror = function() { ???????????????layer.msg(‘座椅连接失败!‘); ?????????????????return false; ???????????}

html5 WebSocket

原文地址:https://www.cnblogs.com/tine/p/8383834.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved