HTML 5 Web Sockets应用初探(4)
第八步:关闭Socket
关闭Socket操作相当简单,添加对断开连接按钮的click事件监听就可以。
$('#disconnect').click(function(){
socket.close();
});
完整JavaScript代码
$(document).ready(function() {
if(!("Web Socket" in window)){
$('#chatLog, input, button, #examples').fadeOut("fast");
$('<p>Oh no, you need a browser that supports Web Sockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
}else{
//The user has Web Sockets
connect();
function connect(){
var socket;
var host = "ws://localhost:8000/socket/server/startDaemon.php";
try{
var socket = new Web Socket(host);
message('<p class="event">Socket Status: '+socket.readyState);
socket.onopen = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (open)');
}
socket.onmessage = function(msg){
message('<p class="message">Received: '+msg.data);
}
socket.onclose = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
}
} catch(exception){
message('<p>Error'+exception);
}
function send(){
var text = $('#text').val();
if(text==""){
message('<p class="warning">Please enter a message');
return ;
}
try{
socket.send(text);
message('<p class="event">Sent: '+text)
} catch(exception){
message('<p class="warning">');
}
$('#text').val("");
}
function message(msg){
$('#chatLog').append(msg+'</p>');
}
$('#text').keypress(function(event) {
if (event.keyCode == '13') {
send();
}
});
$('#disconnect').click(function(){
socket.close();
});
}//End connect
}//End else
});
第九步:运行Web Socket服务器
我们要输入一些命令行,XAMPP提供了比较方便的shell选项。点击XAMPP控制面板的’shell’按钮并输入:
php -q path\to\server.php
现在你已经运行了Web Socket服务器!
大功告成!
当页面读取后,将尝试创建一个Web Socket连接,然后用户可以输入信息并从服务器接收信息。大家可以通过The Web Socket API了解HTML 5 Web Socket的最新动态。