`
javatoyou
  • 浏览: 1018717 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

WebSocket

 
阅读更多

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.

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.

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.

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.

// 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.

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.

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:

  • 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.
  • 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.

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.

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 NodeJS which looks very much like the client side API.

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:

<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:

// 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:

  • WebSocket
  • Flash Socket
  • AJAX long-polling
  • AJAX multipart streaming
  • IFrame
  • JSONP polling

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

  • port - the port to connect to
  • transports - an array containing the different transport types in order by preference []
  • transportOptions - an object with additional properties to pass to the transport

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.

NodeJS - 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.

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 NodeJS installed) from command line with:

node socket-server.js

Now your client and server can push messages back and forth! Within the NodeJS script, you can create a periodical message sender using some simple 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 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:

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.

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 Resources

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

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 NodeJS 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!

分享到:
评论

相关推荐

    基于WebAssembly和WebSocket的前端播放器

    基于WebAssembly和WebSocket的前端播放器 通过WebSocket协议,将视频流从回调函数取出通过Wasm解码在前端播放 WebSocket客户端文件夹是参考资料,可看可不看(感兴趣的可以瞅一眼)。 JSWebSocket文件夹中是完整的...

    javax.websocket-api-1.1-API文档-中文版.zip

    赠送jar包:javax.websocket-api-1.1.jar; 赠送原API文档:javax.websocket-api-1.1-javadoc.jar; 赠送源代码:javax.websocket-api-1.1-sources.jar; 赠送Maven依赖信息文件:javax.websocket-api-1.1.pom; ...

    jakarta.websocket-api-1.1.2-API文档-中文版.zip

    赠送jar包:jakarta.websocket-api-1.1.2.jar; 赠送原API文档:jakarta.websocket-api-1.1.2-javadoc.jar; 赠送源代码:jakarta.websocket-api-1.1.2-sources.jar; 赠送Maven依赖信息文件:jakarta.websocket-api...

    详解微信小程序实现WebSocket心跳重连

    最近在开发小程序用到了WebSocket,小程序提供了相应的原生API,与H5的API使用方式上有一些区别,所以流行的H5的一些成熟的类库使用起来有些困难,而原生API又存在一些缺陷,所以就自己实现了一套心跳重连机制。...

    websocket-api-9.4.11.v20180605-API文档-中文版.zip

    赠送jar包:websocket-api-9.4.11.v20180605.jar; 赠送原API文档:websocket-api-9.4.11.v20180605-javadoc.jar; 赠送源代码:websocket-api-9.4.11.v20180605-sources.jar; 赠送Maven依赖信息文件:websocket-...

    jakarta.websocket-api-1.1.2-API文档-中英对照版.zip

    赠送jar包:jakarta.websocket-api-1.1.2.jar; 赠送原API文档:jakarta.websocket-api-1.1.2-javadoc.jar; 赠送源代码:jakarta.websocket-api-1.1.2-sources.jar; 赠送Maven依赖信息文件:jakarta.websocket-api...

    微信小程序webSocket的使用方法

    本篇博客介绍微信小程序中webSocket的使用方法,以及如何用局部网络建立webSocket连接,进行客户端与服务器之间的对话: webSocket简介 微信小程序端API调用 服务器端使用nodejs配置 演示websocket webSocket...

    Android WebSocket实现即时通讯功能

    使用Java-WebSocket开源框架开发Android端即时通讯功能。主要功能: 1、与websocket建立长连接 2、与websocket进行即时通讯 3、Service和Activity之间通讯和UI更新 4、弹出消息通知(包括锁屏通知) 5、心跳检测和重...

    jmeter4.0加插件websocket包,共7个,完整

    可用于 websocket接口测试! Jmeter的WebSocket协议支持插件: JMeterWebSocketSampler-1.0.2-SNAPSHOT.jar 所需依赖包: 1、jetty-http-9.1.2.v20140210.jar 2、jetty-io-9.1.2.v20140210.jar 3、jetty-util-9.1.2....

    java-websocket-1.3.0.jar

    websocket

    java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统.zip

    Java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统。一个基于Spring Boot + WebSocket + Redis,可快速开发的分布式即时通讯群聊系统。适用于直播间聊天、游戏内聊天、客服聊天等临时性群聊场景。 ...

    websocket-cluster:这是一个针对WebSocket集群服务器的Spring Cloud项目。

    实战Spring Cloud的WebSocket体现此项目是一个WebSocket实施的实践,基于Spring Cloud。原理我们利用一致性哈希算法,构造一个哈希环,网关监听WebSocket服务实例的上下线消息,根据实例的变化动态地更新哈希环。将...

    DelphiWebsockets-master.zip_delphi websocket_websocket_websocket

    WebSocket for Delphi

    websocket实现前后台数据更新

    1、前端页面 ... 2、javascript websocket.js,websocket页面使用javascript...WebSocketServer.java、WebSocketConfig.java 定义后台onopen、onmessage、onclose、onerror函数及信息发送函数,提供给websoceket功能支持。

    一个简单的网页 Websocket 连接并实现心跳 Heartbeat

    let ws = new WebSocket('wss://echo.websocket.org/'); 然后是通过回调函数获取服务器消息以及对连接状态进行捕捉。 // 成功连接时触发 ws.onopen = () =&gt; { console.log('连接成功.'); this.send('{event:...

    websocket_for_linux-master_websocket_websocket客户端_WEBSOCKET单片机实现

    5WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。...

    基于node+vue实现简单的WebSocket聊天功能

    首先,我需要用到node的nodejs-websocket模块 使用yarn进行安装 yarn add nodejs-websocket –save 当然,你也可以用npm进行安装 npm i nodejs-websocket –save 安装完毕之后,我们开始写服务端的代码,首先,...

    Uniapp使用GoEasy实现websocket实时通讯

    Uniapp作为近来最火的移动端开发技术,一套代码,可以打包成Android/iOS app和各种平台的小程序,可谓是没有最方便只有更方便。 GoEasy上架DCloud Uniapp...Uniapp官方的websocket API主要是用来与您的websocket服务

    Android 实现WebSocket长连接

    Android 实现WebSocket长连接 最近项目中引入了实时接收服务器数据的功能,考量后通过WebSocket长链接来实现。 1、建立在 TCP 协议之上,服务器端的实现比较容易。 2、与 HTTP 协议有着良好的兼容性。默认端口也是80...

    python实现WebSocket服务端过程解析

    一种类似Flask开发的WebSocket-Server服务端框架,适用python3.X 1、安装模块Pywss pip install pywss 2、搭建简易服务器 2.1 服务端代码 代码简介 route: 注册请求路径 example_1(request, data): request: ...

Global site tag (gtag.js) - Google Analytics