Created
June 3, 2012 09:41
-
-
Save dfhe2004/2862776 to your computer and use it in GitHub Desktop.
websocket client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>WebSocket</title> | |
<style> | |
html,body{font:normal 0.9em arial,helvetica;} | |
#log {width:440px; height:200px; border:1px solid #7F9DB9; overflow:auto;} | |
#msg {width:330px;} | |
</style> | |
<script> | |
var socket; | |
function init(){ | |
var host = "ws://localhost:8080/ws/test"; | |
try{ | |
socket = new WebSocket(host); | |
socket.onopen = function(msg){ ; }; | |
socket.onmessage = function(msg){ log(msg.data); }; | |
socket.onclose = function(msg){ log("Lose Connection!"); }; | |
} | |
catch(ex){ log(ex); } | |
$("msg").focus(); | |
} | |
function send(){ | |
var txt,msg; | |
txt = $("msg"); | |
msg = txt.value; | |
if(!msg){ alert("Message can not be empty"); return; } | |
txt.value=""; | |
txt.focus(); | |
try{ socket.send(msg); } catch(ex){ log(ex); } | |
} | |
window.onbeforeunload=function(){ | |
try{ | |
socket.send('quit'); | |
socket.close(); | |
socket=null; | |
} | |
catch(ex){ | |
log(ex); | |
} | |
}; | |
function $(id){ return document.getElementById(id); } | |
function log(msg){ $("log").innerHTML+="<br>"+msg; } | |
function onkey(event){ if(event.keyCode==13){ send(); } } | |
</script> | |
</head> | |
<body onload="init()"> | |
<h3>WebSocket</h3> | |
<br><br> | |
<div id="log"></div> | |
<input id="msg" type="textbox" onkeypress="onkey(event)"/> | |
<button onclick="send()">发送</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment