123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <!DOCTYPE html>
- <html>
- <head>
- <title>Socket</title>
- </head>
- <body">
- <div><input type="text" id="textin"><button onclick="send()">Submit</button> <button onclick="Broadcast()">Submit to room</button></div>
- <input type="text" id="roomid"><button onclick="joinTheRoom()">JOIN</button><br />
- <input type="text" id="WS-SERVER" value="ws://localhost:3000"><button onclick="InitWS()">Connect</button>
- <script>
- 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(document.getElementById('WS-SERVER').value);
- 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");
- }
- }
- </script>
- </body>
- </html>
|