websocket socket WebRTC

90 阅读5分钟

WebSocket与Socket的关系

Socket其实并不是一个协议,而是为了方便使用TCP或UDP而抽象出来的一层,是位于应用层和传输控制层之间的一组接口。

Socket是传输控制层协议,WebSocket是应用层协议。

在设计模式中,Socket其实就是一个门面模式

websocket vs WebRTC (Web Real-Time Communications)

ably.com/topic/webrt…

  • WebSocket provides a client-server computer communication protocol, whereas WebRTC offers a peer-to-peer protocol and communication capabilities for browsers and mobile apps.
  • While WebSocket works only over TCP, WebRTC is primarily used over UDP (although it can work over TCP as well).
  • WebSocket is a better choice when data integrity is crucial, as you benefit from the underlying reliability of TCP. On the other hand, if speed is more important and losing some packets is acceptable, WebRTC over UDP is a better choice.
  • WebRTC is primarily designed for streaming audio and video content. It is possible to stream media with WebSockets too, but the WebSocket technology is better suited for transmitting text/string data using formats such as JSON.

When to use WebRTC?

WebRTC is a good choice for the following use cases:

  • Audio and video communications, such as video calls, video chat, video conferencing, and browser-based VoIP.
  • File sharing apps.
  • Screen sharing apps.
  • Broadcasting live events (such as sports events).
  • IoT devices (e.g., drones or baby monitors streaming live audio and video data).

When to use WebSockets?

We can broadly group Web Sockets use cases into two distinct categories:

  • Realtime updates, where the communication is unidirectional, and the server is streaming low-latency (and often frequent) updates to the client. Think of live score updates or alerts and notifications, to name just a few use cases.
  • Bidirectional communication, where both the client and the server send and receive messages. Examples include chat, virtual events, and virtual classrooms (the last two usually involve features like live polls, quizzes, and Q&As). WebSockets can also be used to underpin multi-user synchronized collaboration functionality, such as multiple people editing the same document simultaneously.

When to use WebRTC and WebSocket together?

WebSockets and WebRTC are complementary technologies. As mentioned before, WebRTC allows for peer-to-peer communication, but it still needs servers, so that these peers can coordinate communication, through a process called signaling. Generally, signaling involves transferring information such as media metadata (e.g., codecs and media types), network data (for example, the host’s IP address and port), and session-control messages for opening and closing communication.  

A key thing to bear in mind: WebRTC does not provide a standard signaling implementation, allowing developers to use different protocols for this purpose. The WebSocket protocol is often used as a signaling mechanism for WebRTC applications, allowing peers to exchange network and media metadata in realtime.

image.png

websocket

我们知道 TCP 连接的两端,同一时间里双方都可以主动向对方发送数据。这就是所谓的全双工

而现在使用最广泛的HTTP1.1,也是基于 TCP 协议的,同一时间里,客户端和服务器只能有一方主动发数据,这就是所谓的半双工

也就是说,好好的全双工 TCP,被 HTTP 用成了半双工。

为什么?

这是由于 HTTP 协议设计之初,考虑的是看看网页文本的场景,能做到客户端发起请求再由服务器响应,就够了,根本就没考虑网页游戏这种,客户端和服务器之间都要互相主动发大量数据的场景。

所以为了更好的支持这样的场景,我们需要另外一个基于 TCP 的新协议

于是新的应用层协议websocket就被设计出来了。

[怎么建立 websocket 连接]

我们平时刷网页,一般都是在浏览器上刷的,一会刷刷图文,这时候用的是HTTP 协议,一会打开网页游戏,这时候就得切换成我们新介绍的websocket 协议

为了兼容这些使用场景。浏览器在TCP 三次握手建立连接之后,都统一使用 HTTP 协议先进行一次通信。

  • 如果此时是普通的 HTTP 请求,那后续双方就还是老样子继续用普通 HTTP 协议进行交互,这点没啥疑问。
  • 如果这时候是想建立 websocket 连接,就会在 HTTP 请求里带上一些特殊的 header 头
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: T2a6wZlAwhgQNqruZ2YUyg==\r\n

这些 header 头的意思是,浏览器想升级协议(Connection: Upgrade) ,并且想升级成 websocket 协议(Upgrade: websocket)

同时带上一段随机生成的 base64 码(Sec-WebSocket-Key) ,发给服务器。

如果服务器正好支持升级成 websocket 协议。就会走 websocket 握手流程,同时根据客户端生成的 base64 码,用某个公开的算法变成另一段字符串,放在 HTTP 响应的 Sec-WebSocket-Accept 头里,同时带上101状态码,发回给浏览器。

HTTP/1.1 101 Switching Protocols\r\n
Sec-WebSocket-Accept: iBJKv/ALIW2DobfoA4dmr3JHBCY=\r\n
Upgrade: websocket\r\n
Connection: Upgrade\r\n

之后,浏览器也用同样的公开算法base64码转成另一段字符串,如果这段字符串跟服务器传回来的字符串一致,那验证通过。

image.png

websocket 和 HTTP 一样都是基于 TCP 的协议。经历了三次 TCP 握手之后,利用 HTTP 协议升级为 websocket 协议。

WebRTC (Web Real-Time Communications)

WebRTC(Web Real-Time Communications)允许网络应用之间 建立 点对点(Peer-to-Peer)的连接,实现音、视频流和 任意二进制数据的传输。

WebRTC protocols

developer.mozilla.org/en-US/docs/…

[ICE]

[Interactive Connectivity Establishment (ICE)] is a framework to allow your web browser to connect with peers. There are many reasons why a straight up connection from Peer A to Peer B won't work. It needs to bypass firewalls that would prevent opening connections, give you a unique address if like most situations your device doesn't have a public IP address, and relay data through a server if your router doesn't allow you to directly connect with peers. ICE uses STUN and/or TURN servers to accomplish this, as described below.

[STUN]

Session Traversal Utilities for NAT (STUN) is a protocol to discover your public address and determine any restrictions in your router that would prevent a direct connection with a peer.

The client will send a request to a STUN server on the Internet who will reply with the client's public address and whether or not the client is accessible behind the router's NAT.

NAT (Network Address Translation)

[Network Address Translation (NAT)]is used to give your device a public IP address. A router will have a public IP address and every device connected to the router will have a private IP address. Requests will be translated from the device's private IP to the router's public IP with a unique port.

Some routers will have restrictions on who can connect to devices on the network. This can mean that even though we have the public IP address found by the STUN server, not anyone can create a connection. In this situation we need to use TURN.

TURN (Traversal Using Relays around NAT)

Some routers using NAT employ a restriction called 'Symmetric NAT'. This means the router will only accept connections from peers you've previously connected to.

[Traversal Using Relays around NAT (TURN)] is meant to bypass the Symmetric NAT restriction by opening a connection with a TURN server and relaying all information through that server. You would create a connection with a TURN server and tell all peers to send packets to the server which will then be forwarded to you. This obviously comes with some overhead so it is only used if there are no other alternatives.

image.png

[SDP](Session Description Protocol)

[Session Description Protocol (SDP)]is a standard for describing the multimedia content of the connection such as resolution, formats, codecs (/ˈkəʊ.dek/[编码译码工具]), encryption, etc. so that both peers can understand each other once the data is transferring. This is, in essence, the metadata describing the content and not the media content itself.