只专注于客户端的API,因为每个服务器端语言有自己的API。下面的代码片段是打开一个连接,为连接创建事件监听器,断开连接,消息时间,发送消息返回到服务器,关闭连接。
// 创建一个Socket实例
var socket = new WebSocket('ws://localhost:8080');
// 打开Socket
socket.onopen = function(event) {
// 发送一个初始化消息
socket.send('I am the client and I\'m listening!');
// 监听消息
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// 监听Socket的关闭
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
// 关闭Socket....
//socket.close()
}; 此时,Socket.IO在此页面上是有效的,是时候创建Socket了:
// 创建Socket.IO实例,建立连接
var socket= new io.Socket('localhost',{
port: 8080
});
socket.connect();
// 添加一个连接监听器
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// 添加一个连接监听器
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// 添加一个关闭连接的监听器
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// 通过Socket发送一条消息到服务器
function sendMessageToServer(message) {
socket.send(message);
} Socket.IO简化了WebSocket API,统一了返回运输的API。传输包括:
WebSocket
Flash Socket
AJAX long-polling
AJAX multipart streaming
IFrame
JSONP polling
你还可以设置任意的Socket.IO构造器的第二个选项,选项包括:
port - 待连接的端口
transports - 一个数组,包含不同的传输类型
transportOptions - 传输的参数使用的对象,带附加属性
Socket.IO还提供了由本地WebSocket API提供的普通连接、断开连接、消息事件。Socket还提供了封装每个事件类型的方法。
四、NodeJS和Socket.IO联合开发
Socket.IO提供的服务器端解决方案,允许统一的客户端和服务器端的API。使用Node,你可以创建一个典型的HTTP服务器,然后把服务器的实例传递到Socket.IO。从这里,你创建连接、断开连接、建立消息监听器,跟在客户端一样。
一个简单的服务器端脚本看起来如下:
// 需要HTTP 模块来启动服务器和Socket.IO
var http= require('http'), io= require('socket.io');
// 在8080端口启动服务器
var server= http.createServer(function(req, res){
// 发送HTML的headers和message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('Hello Socket Lover! ');
});
server.listen(8080);
// 创建一个Socket.IO实例,把它传递给服务器
var socket= io.listen(server);
// 添加一个连接监听器
socket.on('connection', function(client){
// 成功!现在开始监听接收到的消息
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
你可以运行服务器部分,假定已安装了NodeJS,从命令行执行:
node socket-server.js
现在客户端和服务器都能来回推送消息了!在NodeJS脚本内,可以使用简单的JavaScript创建一个定期消息发送器:
// 创建一个定期(每5秒)发送消息到客户端的发送器
var interval= setInterval(function() {
client.send('This is a message from the server! ' + new Date().getTime());
},5000); 服务器端将会每5秒推送消息到客户端!
五、dojox.Socket和Socket.IO
Persevere的创建者Kris Zyp创建了dojox.Socket。dojox.Socket以Dojo库一致的方式封装了WebSocket API,用于在客户端不支持WebSocket时,使用long-polling替代。
下面是怎样在客户端使用dojox.Socket和在服务器端使用Socket.IO的例子:
var args, ws= typeof WebSocket!= 'undefined';
var socket= dojox.socket(args= {
url: ws? '/socket.io/websocket' : '/socket.io/xhr-polling',
headers:{
'Content-Type':'application/x-www-urlencoded'
},
transport: function(args, message){
args.content = message; // use URL-encoding to send the message instead of a raw body
dojo.xhrPost(args);
};
});
var sessionId;
socket.on('message', function(){
if (!sessionId){
sessionId= message;
args.url += '/' + sessionId;
}else if(message.substr(0, 3) == '~h~'){
// a heartbeat
}
}); 有很多WebSocke的实际应用。WebSocket对于大多数客户机-服务器的异步通信是理想的,在浏览器内聊天是最突出的应用。WebSocket由于其高效率,被大多数公司所使用。
查看更多关于HTML5的WebSocket详解的详细内容...