window.onload = function(){ InitWS(); } aROOM = 0 function joinTheRoom(){ aROOM = document.getElementById('roomid').value; var Datas = {'tag': 'setRoom', 'msg': aROOM, 'opt': true}; ws.send(JSON.stringify(Datas)); console.log("Join to room " + aROOM); // 结果返回 } function send(){ var context = document.getElementById('textin').value; var data = {'tag': 'public', 'msg': context, 'opt': false}; ws.send(JSON.stringify(data)); } function Broadcast(){ var context = document.getElementById('textin').value; var data = {'tag': 'roomcast', 'msg': context, 'opt': true, 'arg': {'roomid': aROOM}}; ws.send(JSON.stringify(data)); } function InitWS(){ if("WebSocket" in window){ console.log("您的浏览器支持Websocket"); ws = new WebSocket("ws://localhost:3000"); ws.onopen = function(){ console.log("connected!"); } ws.onmessage = function(evt){ var rece = evt.data; console.log("received: "+ rece); } ws.onclose = function(){ console.log("disconnected!"); } }else{ alert("您的浏览器不支持Websocket"); } }