Skip to content

Instantly share code, notes, and snippets.

@mozhu1024
Last active December 24, 2017 16:08
Show Gist options
  • Save mozhu1024/f1db59becc80c0f2da2ba8998d10a3c3 to your computer and use it in GitHub Desktop.
Save mozhu1024/f1db59becc80c0f2da2ba8998d10a3c3 to your computer and use it in GitHub Desktop.
WebSocket for JavaScript
var ws;
function ToggleConnectionClicked() {
try {
ws = new WebSocket("ws://127.0.0.1:2000");//连接服务器
ws.onopen = function(event){alert("已经与服务器建立了连接\r\n当前连接状态:"+this.readyState);};
ws.onmessage = function(event){alert("接收到服务器发送的数据:\r\n"+event.data);};
ws.onclose = function(event){alert("已经与服务器断开连接\r\n当前连接状态:"+this.readyState);};
ws.onerror = function(event){alert("WebSocket异常!");};
} catch (ex) {
alert(ex.message);
}
}
function SendData() {
try{
var content = document.getElementById("content").value;
if(content){
ws.send(content);
}
}catch(ex){
alert(ex.message);
}
}
function seestate(){
alert(ws.readyState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment