WebSocket和Socket.IO

WebSocket Socket.IO

My favorite web technology is quickly becoming the WebSocket API. WebSocket provides a welcomed alternative to the AJAX technologies we've been making use of over the past few years. This new API provides a method to push messages from client to server efficiently and with a simple syntax. Let's take a look at the HTML5 WebSocket API: its use on the client side, server side, and an outstanding wrapper API called Socket.IO.

我最喜欢的Web技术正在Swift成为WebSocket API。 WebSocket提供了过去几年中我们一直在使用的AJAX技术的替代方案。 这个新的API提供了一种使用简单的语法将消息从客户端有效地推送到服务器的方法。 让我们看一下HTML5 WebSocket API:它在客户端,服务器端的使用以及一个出色的包装API(称为Socket.IO)。

什么是WebSocket API? (What is the WebSocket API?)

The WebSocket API is the next generation method of asynchronous communication from client to server. Communication takes place over single TCP socket using the ws (unsecure) or wss (secure) protocol and can be used by any client or server application. WebSocket is currently being standardized by the W3C. WebSocket is currently implemented in Firefox 4, Chrome 4, Opera 10.70, and Safari 5.

WebSocket API是从客户端到服务器的异步通信的下一代方法。 使用ws (不安全)或wss (安全)协议通过单个TCP套接字进行通信,并且任何客户端或服务器应用程序都可以使用该通信。 W3C当前正在对WebSocket进行标准化。 WebSocket当前在Firefox 4,Chrome 4,Opera 10.70和Safari 5中实现。

What's great about the WebSocket API that server and client can push messages to each other at any given time. WebSocket is not limited in its nature the way that AJAX (or XHR) is; AJAX technologies require a request to be made by the client, whereas WebSocket servers and clients can push each other messages. XHR is also limited by domain; the WebSocket API allows cross-domain messaging with no fuss.

服务器和客户端可以在任何给定时间相互推送消息的WebSocket API的优点是什么。 WebSocket本质上不受AJAX(或XHR)限制的方式; AJAX技术要求客户端发出请求,而WebSocket服务器和客户端可以相互推送消息。 XHR也受域限制; WebSocket API允许毫不费力地进行跨域消息传递。

AJAX technology was a clever usage of a feature not designed to be used the way it is today. WebSocket was created for the specific purpose of bi-direction message pushing.

AJAX技术巧妙地使用了一项功能,该功能并非旨在以今天的方式使用。 WebSocket是为双向消息推送的特定目的而创建的。

WebSocket API的用法 (WebSocket API Usage)

Focusing on the client side API only (because each server side language will have its own API), the following snippet opens a connection, creates event listeners for connect, disconnect, and message events, sends a message back to the server, and closes the connection.

以下代码段仅关注客户端API(因为每种服务器端语言将具有其自己的API),因此以下代码段可打开连接,创建连接,断开连接和消息事件的事件侦听器,将消息发送回服务器并关闭连接。


// Create a socket instance
var socket = new WebSocket('ws://localhost:8080');

// Open the socket
socket.onopen = function(event) {
	
	// Send an initial message
	socket.send('I am the client and I\'m listening!');
	
	// Listen for messages
	socket.onmessage = function(event) {
		console.log('Client received a message',event);
	};
	
	// Listen for socket closes
	socket.onclose = function(event) {
		console.log('Client notified socket has closed',event);
	};
	
	// To close the socket....
	//socket.close()
	
};


Let's take a look at the individual pieces of the snippet above. The argument provided to WebSocket represents the URL to the address listening for socket connections. onopen, onclose, and onmessage methods connect you to events on the socket instance. Each of these methods provides an event which gives insight as to the state of the socket.

让我们看一下上面的片段的各个部分。 提供给WebSocket的参数表示侦听套接字连接的地址的URL。 onopenoncloseonmessage方法您连接到插座实例的事件。 这些方法中的每一个都提供一个事件,该事件可提供有关套接字状态的见解。

The onmessage event provides a data property which contains the body of the message. The message body must be a string, so serialization/deserialization strategies will be needed to pass more data.

onmessage事件提供了一个包含消息正文的data属性。 消息正文必须是字符串,因此将需要序列化/反序列化策略来传递更多数据。

The syntax is extremely simple which makes using WebSockets incredibly easy...unless the client doesn't support WebSocket. Internet Explorer does not currently support WebSocket. There are a few fallback transports that you can use if the client doesn't support WebSocket:

语法非常简单,这使得使用WebSockets非常容易...除非客户端不支持WebSocket。 Internet Explorer当前不支持WebSocket。 如果客户端不支持WebSocket,则可以使用一些后备传输:

  • Flash - Flash can provide a simple alternative. The obvious drawback is that Flash is not installed on all clients, and in the case of the iPhone/iPad, cannot be.

    Flash -Flash可以提供简单的替代方法。 明显的缺点是未在所有客户端上都安装Flash,而对于iPhone / iPad,则不能安装Flash。

  • AJAX Long-Polling - AJAX long-polling has been used for quite a while to simulate WebSocket. It's a technology that works but isn't optimized for message sending. I wouldn't call AJAX long-polling a hack but it's simply not an optimal method.

    AJAX长轮询 -AJAX长轮询已用于模拟WebSocket已有相当长的时间了。 这是一项有效的技术,但并未针对消息发送进行优化。 我不会将AJAX称为长期轮询技术,但这并不是最佳方法。

Wouldn't it be great if an API was available that would provide WebSocket event handling, fallback transports, and a server side solution, all within one API? Luckily Guillermo Rauch has created Socket.IO.

如果有一个API可以在一个API中全部提供WebSocket事件处理,后备传输和服务器端解决方案,那不是很好吗? 幸运的是, Guillermo Rauch创建了Socket.IO

带Socket.IO的WebSocket (WebSocket with Socket.IO)

Socket.IO is a WebSocket API created by Guillermo Rauch, CTO of LearnBoost and lead scientist of LearnBoost Labs. Socket.IO will use feature detection to decide if the connection will be established with WebSocket, AJAX long polling, Flash, etc., making creating realtime apps that work everywhere a snap. Socket.IO also provides an API for Node.js which looks very much like the client side API.

Socket.IO是由吉列尔莫·劳赫的CTO创建的WebSocket API LearnBoost和LearnBoost实验室的首席科学家。 Socket.IO将使用功能检测来确定是否将通过WebSocket,AJAX长轮询,Flash等来建立连接,从而使创建可在任何地方正常工作的实时应用变得容易。 Socket.IO还为Node.js提供了一个API,该API非常类似于客户端API。

客户端-Socket.IO设置 (Client - Socket.IO Setup)

Socket.IO is available for download at GitHub. You can include the socket.io.js file or you can pull Socket.IO from CDN:

Socket.IO可从GitHub下载。 您可以包含socket.io.js文件,也可以从CDN中提取Socket.IO:


<script src="http://cdn.socket.io/stable/socket.io.js"></script>


With Socket.IO available in the page, it's time to create a Socket:

通过页面中提供的Socket.IO,现在该创建一个Socket了:


// Create SocketIO instance, connect
var socket = new io.Socket('localhost',{
	port: 8080
});
socket.connect(); 

// Add a connect listener
socket.on('connect',function() {
	console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
	console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
	console.log('The client has disconnected!');
});

// Sends a message to the server via sockets
function sendMessageToServer(message) {
	socket.send(message);
}

Socket.IO simplifies the WebSocket API and unifies the APIs of its fallback transports. Transports include:

Socket.IO简化了WebSocket API,并统一了API的后备传输。 运输包括:

  • WebSocket

    WebSocket
  • Flash Socket

    闪光灯插座
  • AJAX long-polling

    AJAX长轮询
  • AJAX multipart streaming

    AJAX多部分流
  • IFrame

    内嵌框架
  • JSONP polling

    JSONP轮询

You may set any of the Socket.IO instance's options with a second argument to the constructor. Options include:

您可以使用构造函数的第二个参数来设置Socket.IO实例的任何选项。 选项包括:

  • port - the port to connect to

    port要连接的端口

  • transports - an array containing the different transport types in order by preference []

    transports包含按优先级顺序排列的不同传输类型的数组[]

  • transportOptions - an object with additional properties to pass to the transport

    transportOptions具有其他属性的对象,可传递给运输工具

Socket.IO also provides the usual connect, disconnect, and message events that the native WebSocket API provides. Socket also provides an on method which wraps each event type, much the way Node does.

Socket.IO还提供本机WebSocket API提供的常规连接,断开连接和消息事件。 Socket还提供了一个on方法,该方法包装每种事件类型,这与Node一样。

Node.js-Socket.IO设置 (Node.js - Socket.IO Setup)

The server side solution provided by Socket.IO allows unification of the client and server side APIs. With Node, you create a typical HTTP server but then pass the server instance to SocketIO. From there, you create connection, disconnect, and message listeners much the way you did on the client side.

Socket.IO提供的服务器端解决方案允许客户端和服务器端API的统一。 使用Node,您可以创建典型的HTTP服务器,然后将服务器实例传递给SocketIO。 从那里开始,您可以像在客户端那样创建连接,断开连接和消息侦听器。

A sample server side script would look very much like this:

一个示例服务器端脚本看起来非常像这样:


// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){ 

	// Send HTML headers and message
	res.writeHead(200,{ 'Content-Type': 'text/html' }); 
	res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 
	
	// Success!  Now listen to messages to be received
	client.on('message',function(event){ 
		console.log('Received message from client!',event);
	});
	client.on('disconnect',function(){
		clearInterval(interval);
		console.log('Server has disconnected');
	});

});


You can run the server portion (assuming you have Node.js installed) from command line with:

您可以使用以下命令从命令行运行服务器部分(假设已安装Node.js):

node socket-server.js
	

Now your client and server can push messages back and forth! Within the Node.js script, you can create a periodical message sender using some simple JavaScript:

现在,您的客户端和服务器可以来回推送消息! 在Node.js脚本中,您可以使用一些简单JavaScript创建定期邮件发件人:


// Create periodical which ends a message to the client every 5 seconds
var interval = setInterval(function() {
	client.send('This is a message from the server!  ' + new Date().getTime());
},5000);

	

The server side script will push a message to the client every five seconds!

服务器端脚本将每五秒钟向客户端推送一条消息!

dojox.Socket和Socket.IO (dojox.Socket and Socket.IO)

Persevere creator Kris Zyp has created dojox.Socket. dojox.Socket wraps the WebSocket API in an API consistent with Dojo and provides a long-polling alternative if the client doesn't support WebSocket. Here's how you can use dojox.Socket on the client side and Socket.IO on the server side:

坚持不懈的创造者Kris Zyp创建了dojox.Socketdojox.Socket将WebSocket API包装在与Dojo一致的API中,如果客户端不支持WebSocket,则提供长轮询的替代方法。 这是在客户端使用dojox.Socket在服务器端使用dojox.Socket的方法:


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
	}
});

dojox.socket.Reconnect has also been created to automatically reconnect if the socket loses connection. Look forward to dojox.Socket debuting in Dojo 1.6.

还创建了dojox.socket.Reconnect以在套接字断开连接时自动重新连接。 期待dojox.Socket在Dojo 1.6中首次亮相。

实际应用 (Practical Applications)

There are many practical applications for WebSocket. WebSocket is ideal for most client-to-server asynchronous purposes, chat within the browser being the most prominent. WebSocket is used to day by most many companies because of its efficiency. Socket.IO is in use by many organizations and was very popular at the Node KnockOut contest.

WebSocket有许多实际的应用程序。 WebSocket是大多数客户端到服务器异步目的的理想选择,其中最突出的是在浏览器中进行聊天。 由于其效率,WebSocket已被许多公司普遍使用。 Socket.IO已被许多组织使用,并且在Node KnockOut竞赛中非常受欢迎。

WebSocket资源 (WebSocket Resources)

There's not a great deal of information available about WebSocket so I've rounded up a few helpful resources:

关于WebSocket的信息不多,因此我整理了一些有用的资源:

Take a moment to download my demo and visit the resources provided above. The WebSocket API is the future of asynchronous messaging; Socket.IO is the best available resource for WebSocket in Node.js and within the browser. Let me know your thoughts on WebSocket as I'm curious to know if you're as excited as I am by this new API!

花一点时间下载我的演示并访问上面提供的资源。 WebSocket API是异步消息传递的未来。 Socket.IO是Node.js和浏览器中WebSocket的最佳可用资源。 让我知道您对WebSocket的想法,我很想知道您是否对这个新API感到兴奋!

翻译自: https://davidwalsh.name/websocket

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值