Websocket定义

自Google Chrome开发者频道发布4.0.249.0版本起,默认启用了WebSocket功能。WebSocket作为下一代双向通信技术,简化了浏览器与服务器间的交互过程。与XMLHttpRequest相比,WebSocket提供了真正的双向通信通道。

 

看看W3C在HTML5里对于WebSocket的接口定义:

 

interface WebSocket {
  readonly attribute DOMString URL;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSED = 2;
  readonly attribute unsigned short readyState;
  readonly attribute unsigned long bufferedAmount;

  // networking
           attribute Function onopen;
           attribute Function onmessage;
           attribute Function onclose;
  boolean send(in DOMString data);
  void close();
};
WebSocket implements EventTarget;

Web Sockets Now Available In Google Chrome

 

Wednesday, December 09, 2009

Labels: html5, webkit, websockets

 

Starting in the Google Chrome developer channel release 4.0.249.0, Web Sockets are available and enabled by default. Web Sockets are "TCP for the Web," a next-generation bidirectional communication technology for web applications being standardized in part of Web Applications 1.0. We've implemented this feature as described in our design docs for WebKit and Chromium.
The Web Sockets API enables web applications to handle bidirectional communications with server-side process in a straightforward way. Developers have been using XMLHttpRequest("XHR") for such purposes, but XHR makes developing web applications that communicate back and forth to the server unnecessarily complex. XHR is basically asynchronous HTTP, and because you need to use a tricky technique like long-hanging GET for sending data from the server to the browser, simple tasks rapidly become complex. As opposed to XMLHttpRequest, Web Sockets provide a real bidirectional communication channel in your browser. Once you get a Web Socket connection, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. A simple example is included below.
if ("WebSocket" in window) {
  var ws = new WebSocket("ws://example.com/service");
  ws.onopen = function() {
    // Web Socket is connected. You can send data by send() method.
    ws.send("message to send"); ....
  };
  ws.onmessage = function (evt) { var received_msg = evt.data; ... };
  ws.onclose = function() { // websocket is closed. };
} else {
  // the browser doesn't support WebSocket.
}
In addition to the new Web Sockets API, there is also a new protocol (the " web socket protocol") that the browser uses to communicate with servers. The protocol is not raw TCP because it needs to provide the browser's "same-origin" security model. It's also not HTTP because web socket traffic differers from HTTP's request-response model. Web socket communications using the new web socket protocol should use less bandwidth because, unlike a series of XHRs and hanging GETs, no headers are exchanged once the single connection has been established. To use this new API and protocol and take advantage of the simpler programming model and more efficient network traffic, you do need a new server implementation to communicate with — but don't worry. We also developed pywebsocket, which can be used as an Apache extension module, or can even be run as standalone server.
You can use Google Chrome and pywebsocket to start implementing Web Socket-enabled web applications now. We're more than happy to hear your feedback not only on our implementation, but also on API and/or protocol design. The protocol has not been completely locked down and is still in discussion in IETF, so we are especially grateful for any early adopter feedback.
WebSocket 是一种基于 TCP 协议的全双工通信协议,允许客户端和服务器之间建立持久连接并进行双向数据传输。定义 WebSocket 接口的方法和规范需要从协议标准、握手过程、数据帧格式、通信流程等多个方面进行设计和实现。 ### 协议规范 WebSocket 协议的核心规范由 IETF 标准 RFC 6455 定义,并由 RFC 7936 进行补充说明。该协议的设计目标是与 HTTP 协议兼容,同时支持双向通信[^2]。在定义接口时,应确保其符合这些标准,包括握手流程、帧格式、操作码、掩码机制等。 ### 握手过程 WebSocket 的握手过程是通过 HTTP 协议完成的,客户端发送一个带有 `Upgrade: websocket` 头的 HTTP 请求,服务器响应同样的头信息以确认切换协议。握手请求中还包含 `Sec-WebSocket-Key` 字段,服务器使用该字段生成 `Sec-WebSocket-Accept` 响应头以完成验证[^4]。 示例客户端握手请求: ```http GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 ``` 服务器响应: ```http HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat ``` ### 数据帧格式 WebSocket 数据以帧的形式传输,帧的格式包括帧头和有效载荷。帧头包含操作码(opcode)、掩码、载荷长度等字段。操作码定义了帧的类型,如文本帧(0x1)、二进制帧(0x2)、关闭帧(0x8)、Ping(0x9)和 Pong(0xA)等。数据帧的结构必须符合 RFC 6455定义,确保数据的正确解析和处理。 ### 接口方法定义 在应用层定义 WebSocket 接口时,通常包括以下几个关键方法: - `onOpen`:连接建立时触发。 - `onMessage`:接收到消息时触发。 - `onError`:发生错误时触发。 - `onClose`:连接关闭时触发。 以下是一个使用 Python 的 `websockets` 库实现 WebSocket 服务器端的示例: ```python import asyncio import websockets async def echo(websocket, path): async for message in websocket: print(f"Received message: {message}") await websocket.send(f"Echo: {message}") start_server = websockets.serve(echo, "localhost", 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() ``` 对应的客户端连接示例: ```python import asyncio import websockets async def hello(): async with websockets.connect("ws://localhost:8765") as websocket: await websocket.send("Hello Server") response = await websocket.recv() print(f"Received: {response}") asyncio.get_event_loop().run_until_complete(hello()) ``` ### 接口规范设计 在设计 WebSocket 接口规范时,应明确以下几点: 1. **消息格式**:建议使用 JSON 或 Protobuf 等结构化格式进行数据交换。 2. **错误处理机制**:定义错误码和错误描述,便于客户端和服务器处理异常情况。 3. **连接保持与重连机制**:通过 Ping/Pong 帧保持连接活跃,并在断开时实现自动重连。 4. **安全性**:使用 `wss://` 协议进行加密通信,并结合 Token 或 Cookie 实现身份验证。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值