转自:
http://blog.youkuaiyun.com/jiht594/article/details/43764941
客户端
参考: 用Python实现一个简单的WebSocket服务器
测试了chrome37, firefox35
- >
- <</span>html>
- <</span>head>
- <</span>title>WebSocket</</span>title>
- <</span>style>
- html, body {
- font: normal 0.9em arial, helvetica;
- }
- #log {
- width: 440px;
- height: 200px;
- border: 1px solid #7F9DB9;
- overflow: auto;
- }
- #msg {
- width: 330px;
- }
- </</span>style>
- <</span>script>
- var socket;
- function init() {
- var host = "ws://127.0.0.1:12345/";
- try {
- socket = new WebSocket(host);
- socket.onopen = function (msg) {
- log('Connected');
- };
- 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.getElementByIdx_x(id);
- }
- function log(msg) {
- $("log").innerHTML += "<</span>br>" + msg;
- }
- function onkey(event) {
- if (event.keyCode == 13) {
- send();
- }
- }
- </</span>script>
- </</span>head>
- <</span>body onload="init()">
- <</span>h3>WebSocket</</span>h3>
- <</span>br><</span>br>
- <</span>div id="log"></</span>div>
- <</span>input id="msg" type="textbox" onkeypress="onkey(event)"/>
- <</span>button onclick="send()">发送</</span>button>
- </</span>body>
- </</span>html>
参考: 用Python实现一个简单的WebSocket服务器
由于使用125, 126, 127用作标志位.