52 lines
1.7 KiB
HTML
52 lines
1.7 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Socket</title>
|
|
</head>
|
|
<body onload="InitWS()">
|
|
<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>
|
|
<script>
|
|
aROOM = 0
|
|
function joinTheRoom(){
|
|
aROOM = document.getElementById('roomid').value;
|
|
var Datas = {'tag': 'setRoom', 'msg': aROOM, 'opt': true};
|
|
ws.send(JSON.stringify(Datas));
|
|
// 结果返回
|
|
}
|
|
|
|
function send(){
|
|
var context = document.getElementById('textin').value;
|
|
var data = {'tag': 'roomcast', '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': 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");
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
</html> |