html 代码
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>Jack 张 webSocket 实例 </title>
- <style>
- html,body{font:normal 14px;margin:0 auto;}
- #log {width:440px;
- height:270px;
- text-align:left;
- overflow:auto;margin:0px auto;
- font-weight:bold;color:#F8F8F8;
- background:#000;
- opacity:0.6
- }
- #msg {width:330px;margin:0px auto;}
- #imagebg{
- background-image: url(images/2.jpg);
- background-repeat: no-repeat;
- background-position: center top;
- height:643px;
- overflow:hidden;
- text-align:center;
- padding-top:120px;
- }
- </style>
- <script>
- // 声明一个 socket
- var socket;
- // 初始化方法
- function init(){
- var host = "ws://echo.websocket.org/";// 声明 host 注意: 是 ws 协议
- try{
- socket = new WebSocket(host);// 新创建一个 socket 对象
- log('WebSocket - status'+socket.readyState);// 将连接的状态信息显示在 log
- socket.onopen = function(msg){ log("Welcome - status"+this.readyState); };// 监听打开连接
- socket.onmessage = function(msg){ log("Received:"+msg.data); };// 监听当接收信息时触发匿名函数
- socket.onclose = function(msg){ log("Disconnected - status"+this.readyState); };// 关闭连接
- }
- 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); log('Sent:'+msg); } catch(ex){ log(ex); }
- }
- // 声明一个对开连接, 关闭 socket 方法
- function quit(){
- log("Goodbye!");
- socket.close();
- socket=null;
- }
- // 根据 id 获取 DOM 元素
- function $(id){ return document.getElementById(id); }
- // 将信息显示在 id 为 log 的 div 中
- function log(msg){ $("log").innerHTML+="<br>"+msg; }
- // 键盘事件 (回车)
- function onkey(event){ if(event.keyCode==13){ send(); } }
- </script>
- </head>
- <body onload="init()">
- <div id="imagebg">
- <div style="width:520px;text-align:left;margin:0px auto;color:#000;"> <a href="http://weibo.com/jackyo"><strong> 新浪微博: Jack 张 </strong></a> </div>
- <br>
- <div id="log"></div>
- <input id="msg" type="textbox" onkeypress="onkey(event)"/>
- <button onclick="send()"> 发送 </button>
- <button onclick="quit()"> 断开 </button>
- </div>
- </body>
- </html>
之前没了解, 最近搜了一下, 写的不错, 收藏:
http://blog.csdn.net/cd_cd/article/details/46817667
来源: http://www.qdfuns.com/article/16039/84094a08a8ce0b8e988a2119c2b8962a.html