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