web socket

认识HTML5的WebSocket

在HTML5规范中,我最喜欢的Web技术就是正迅速变得流行的WebSocket API。WebSocket提供了一个受欢迎的技术,以替代我们过去几年一直在用的Ajax技术。这个新的API提供了一个方法,从客户端使用简单的语法有效地推动消息到服务器。让我们看一看HTML5的WebSocket API:它可用于客户端、服务器端。而且有一个优秀的第三方API,名为Socket.IO。

一、什么是WebSocket API?

WebSocket API是下一代客户端-服务器的异步通信方法。该通信取代了单个的TCP套接字,使用ws或wss协议,可用于任意的客户端和服务器程序。WebSocket目前由W3C进行标准化。WebSocket已经受到Firefox 4、Chrome 4、Opera 10.70以及Safari 5等浏览器的支持。


WebSocket API最伟大之处在于服务器和客户端可以在给定的时间范围内的任意时刻,相互推送信息。WebSocket并不限于以Ajax(或XHR)方式通信,因为Ajax技术需要客户端发起请求,而WebSocket服务器和客户端可以彼此相互推送信息;XHR受到域的限制,而WebSocket允许跨域通信。

Ajax技术很聪明的一点是没有设计要使用的方式。WebSocket为指定目标创建,用于双向推送消息。

二、WebSocket API的用法

只专注于客户端的API,因为每个服务器端语言有自己的API。下面的代码片段是打开一个连接,为连接创建事件监听器,断开连接,消息时间,发送消息返回到服务器,关闭连接。

[Copy to clipboard] [ - ]

CODE:

// 创建一个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() 
};


让我们来看看上面的初始化片段。参数为URL,ws表示WebSocket协议。onopen、onclose和onmessage方法把事件连接到Socket实例上。每个方法都提供了一个事件,以表示Socket的状态。

onmessage事件提供了一个data属性,它可以包含消息的Body部分。消息的Body部分必须是一个字符串,可以进行序列化/反序列化操作,以便传递更多的数据。

WebSocket的语法非常简单,使用WebSockets是难以置信的容易……除非客户端不支持WebSocket。IE浏览器目前不支持WebSocket通信。如果你的客户端不支持WebSocket通信,下面有几个后备方案供你使用:

Flash技术 —— Flash可以提供一个简单的替换。 使用Flash最明显的缺点是并非所有客户端都安装了Flash,而且某些客户端,如iPhone/iPad,不支持Flash。

AJAX Long-Polling技术 —— 用AJAX的long-polling来模拟WebSocket在业界已经有一段时间了。它是一个可行的技术,但它不能优化发送的信息。也就是说,它是一个解决方案,但不是最佳的技术方案。

由于目前的IE等浏览器不支持WebSocket,要提供WebSocket的事件处理、返回传输、在服务器端使用一个统一的API,那么该怎么办呢?幸运的是,Guillermo Rauch创建了一个Socket.IO技术。

三、带Socket.IO的WebSocket

Socket.IO是Guillermo Rauch创建的WebSocket API,Guillermo Rauch是LearnBoost公司的首席技术官以及LearnBoost实验室的首席科学家。Socket.IO使用检测功能来判断是否建立WebSocket连接,或者是AJAX long-polling连接,或Flash等。可快速创建实时的应用程序。Socket.IO还提供了一个NodeJS API,它看起来非常像客户端API。

建立客户端Socket.IO

Socket.IO可以从GitHub下载,可以把socket.io.js文件包含到页面中:

[Copy to clipboard] [ - ]

CODE:

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

此时,Socket.IO在此页面上是有效的,是时候创建Socket了:

[code]
//
创建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。从这里,你创建连接、断开连接、建立消息监听器,跟在客户端一样。

一个简单的服务器端脚本看起来如下:

[Copy to clipboard] [ - ]

CODE:

// 需要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('<h1>Hello Socket Lover!</h1>'); 
}); 
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,从命令行执行:

[Copy to clipboard] [ - ]

CODE:

node socket-server.js


现在客户端和服务器都能来回推送消息了!在NodeJS脚本内,可以使用简单的JavaScript创建一个定期消息发送器:

[Copy to clipboard] [ - ]

CODE:

// 创建一个定期(每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的例子:

[Copy to clipboard] [ - ]

CODE:

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还创建了在套接字失去连接时自动重连。期待包含dojox.Socket的Dojo 1.6版本早日发布。

六、实际应用和WebSocket资源

有很多WebSocke的实际应用。WebSocket对于大多数客户机-服务器的异步通信是理想的,在浏览器内聊天是最突出的应用。WebSocket由于其高效率,被大多数公司所使用。

 

WebSocket

From Wikipedia, the free encyclopedia

  (Redirected from WebSockets)

Jump to: navigation, search

WebSocket is a web technology providing full-duplex communications channels over a single TCP connection. The WebSocket API is being standardized by the W3C, and the WebSocket protocol has been standardized by the IETF as RFC 6455.

WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request.[1] The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server. A similar effect has been achieved in non-standardized ways using stop-gap technologies such as Comet.

In addition, the communications are done over TCP port number 80, which is of benefit for those environments which block non-standard Internet connections using afirewall. WebSocket protocol is currently supported in several browsers includingGoogle Chrome,Internet Explorer, Firefox, Safari and Opera. WebSocket also requires web applications on the server to support it.

Contents

 [hide

[edit] Technical overview

Like TCP, WebSocket provides for full-duplex communication. Websocket differs from TCP in that it enables a stream of messages instead of a stream of bytes. Before WebSocket, port 80 full-duplex communication was attainable usingcomet channels; however, comet implementation is nontrivial, and due to the TCP handshake and HTTP header overhead, it is inefficient for small messages. WebSocket protocol aims to solve these problems without compromising security assumptions of the web.

[edit] Browser Implementation

A secure version of the WebSocket protocol is implemented in Firefox 6 (named MozWebSocket),[2] Google Chrome 14[3] and Internet Explorer 10 developer preview.[4]

An older, less secure version of the protocol was implemented in Opera 11 and Safari 5, as well as the mobile version of Safari in iOS 4.2.[5] Also, the BlackBerry Browser in OS7 implements WebSocket.[6] Although there are no known exploits, it was disabled in Firefox 4 and 5,[7] and Opera 11.[8]

[edit] WebSocket protocol handshake

To establish a WebSocket connection, the client sends a WebSocket handshake request, and the server sends a WebSocket handshake response, as shown in the following example:

GET /mychat HTTP/1.1

Host: server.example.com

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==

Sec-WebSocket-Protocol: chat

Sec-WebSocket-Version: 13

Origin: http://example.com

Server response:

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=

Sec-WebSocket-Protocol: chat

The handshake resembles HTTP, but actually isn't. It allows the server to interpret part of the handshake request as HTTP, then switch to WebSocket.

Note that each line ends with an EOL (end of line) sequence, \n or \r\n. There must be a blank line at the end.

The client sends a Sec-WebSocket-Key which is base64 encoded. To form a response, the magic string 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 is appended to this (undecoded) key. The resulting string is then hashed withSHA-1, then base64 encoded. Finally, the resulting reply occurs in the header Sec-WebSocket-Accept.

Details of Sec-WebSocket-Key to Sec-WebSocket-Accept :

  • x3JJHMbDL1EzLkh9GBhXDw==258EAFA5-E914-47DA-95CA-C5AB0DC85B11 string hashed by SHA-1 gives 0x1d29ab734b0c9585240069a6e4e3e91b61da1969 hexadecimal value.
  • Encoding the SHA-1 hash by Base64 yields HSmrc0sMlYUkAGmm5OPpG2HaGWk=, which is the Sec-WebSocket-Accept value.

Once the connection is established, the client and server can send WebSocket data frames back and forth in full-duplex mode. They can send text frames infull-duplex, in either direction at the same time. The data is minimally framed.

[edit] Proxy traversal

WebSocket protocol client implementations try to detect if the user agent is configured to use a proxy when connecting to destination host and port and, if it is, usesHTTP CONNECT method to set up a persistent tunnel.

While the WebSocket protocol itself is unaware of proxy servers and firewalls, it features an HTTP-compatible handshake so that HTTP servers can share their default HTTP and HTTPS ports (80 and 443) with a WebSocket gateway or server. The WebSocket protocol defines a ws:// and wss:// prefix to indicate a WebSocket and a WebSocket Secure connection, respectively. Both schemes use an HTTP upgrade mechanism to upgrade to the WebSocket protocol. Some proxy servers are harmless and work fine with WebSocket; others will prevent WebSocket from working correctly, causing the connection to fail. In some cases, additional proxy server configuration may be required, and certain proxy servers may need to be upgraded to support WebSocket.

If unencrypted WebSocket traffic flows through an explicit or a transparent proxy server on its way to the WebSocket server, then, whether or not the proxy server behaves as it should, the connection is almost certainly bound to fail today (as WebSocket become more mainstream, proxy servers may become WebSocket aware). Therefore, unencrypted WebSocket connections should be used only in the simplest topologies.[9]

If an encrypted WebSocket connection is used, then the use of Transport Layer Security (TLS) in the WebSocket Secure connection ensures that an HTTP CONNECT command is issued when the browser is configured to use an explicit proxy server. This sets up a tunnel, which provides low-level end-to-end TCP communication through the HTTP proxy, between the WebSocket Secure client and the WebSocket server. In the case of transparent proxy servers, the browser is unaware of the proxy server, so no HTTP CONNECT is sent. However, since the wire traffic is encrypted, intermediate transparent proxy servers may simply allow the encrypted traffic through, so there is a much better chance that the WebSocket connection will succeed if WebSocket Secure is used. Using encryption is not free of resource cost, but often provides the highest success rate.

A mid-2010 draft (version hixie-76) broke compatibility with reverse-proxies and gateways by including 8 bytes of key data after the headers, but not advertising that data in a Content-Length: 8 header.[10] This data was not forwarded by all intermediates, which could lead to protocol failure. More recent drafts (e.g., hybi-09[11]) put the key data in a Sec-WebSocket-Key header, solving this problem.

[edit] URI scheme

The WebSocket protocol specification defines two new URI schemes, ws: and wss:,[12] for unencrypted and encrypted connections respectively. Apart from the scheme name, the rest of the URI components are defined to use URI generic syntax.[13]

[edit] Browser support

Chrome 16, Firefox 11, Safari 6, and Internet Explorer 10 are currently the only browsers supporting the latest specification (RFC 6455) of the WebSocket protocol. A detailed protocol test suite report[14] lists the conformance of those browsers to specific protocol aspects.

Firefox 4[15] and Opera 11[16] originally supported the outdated draft-ietf-hybi-thewebsocketprotocol-00 WebSocket, but later disabled the protocol by default due to security issues. Chrome also planned to disable the WebSocket if actual exploit code appeared before the protocol was revised.[17]

Implementation status

Protocol

Internet Explorer

Firefox[18]

Chrome

Safari (Mac, iOS)

Opera

hixie-75

 

 

4

5.0.0

 

hixie-76
hybi-00

 

4.0 (disabled)

6

5.0.1

11.00 (disabled)

7 hybi-07

 

6[19]1

 

 

 

8 hybi-10

 

7[20]1

14[21]

 

 

13 RFC 6455

10 PP5[22]

11

16[23]

6

12.10[24]

1 Gecko-based browsers versions 6–10 implement the WebSocket object as "MozWebSocket",[25] requiring extra code to integrate with existing WebSocket-enabled code.

[edit] Experimental extensions

There is also a command-line switch for Google Chrome (--enable-websocket-over-spdy) that enables an early experimental implementation of WebSocket overSPDY.[26]

[edit] Development

The WebSocket echo service hosted bywebsocket.org offers a simple way to get started with WebSocket development. Using the Google Chrome Developer Tools developers can inspect the WebSocket handshake as well as the WebSocket frames[27].

[edit] See also

 

 

websocket初探

摘要: 应用背景 首先我们了解一下什么是WebSocket。WebSocket是HTML5的重要特性,其通信协议实现的是基于浏览器的远程socket,实现了浏览器和服务器全双工通信(full-duplex)。 在websocket之前,为了实现即时通信,所用 ...

应用背景

首先我们了解一下什么是WebSocket 。WebSocket 是HTML5的重要特性,其通信协议实现的是基于浏览器的远程socket,实现了浏览器和服务器全双工通信(full-duplex)。

在websocket之前,为了实现即时通信,所用的技术都是轮询,在特定的时间间隔内,由浏览器对服务器发出HTTP request,然后由服务器返回最新的数据给客户端的浏览器,这样,浏览器需要对服务器不断发出请求,会占用很多带宽。

在 WebSocket API,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。它解决了web实时化的问题,相比传统http有如下好处:

1)一个WEB客户端只建立一个TCP连接

2)Websocket服务端可以推送(push)数据到web客户端.

3)有更加轻量级的头,减少数据传送量

websocket原理

我们可以把websocket应用看做有两个部分,客户端和服务端。在客户端会实例化一个websocket对象,如:

ws = new WebSocket( “ws://yourdomain:port/path” );

websocket对象会自动解析这段字符串,发送到指定的服务器端口,接着客户端与服务端会建立握手。客户端发送的数据格式类似:

GET /echo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host:
http://www.51wp7.com:8080
Origin: http://www.51wp7.com

服务端应该返回的信息为:

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin:
http://www.51wp7.com
WebSocket-Location: ws:// www.51wp7.com:8080/echo

客户端握手成功后,会触发webscoket对象的onopen事件,告诉客户端连接已经成功建立。

客户端一共绑定了四个事件。

1)onopen 建立连接后触发

2)onmessage 收到消息后触发

3)onerror 发生错误时触发

4)onclose 关闭连接时触发

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值