ws和wss的区别?

Difference between ws and wss?

将 ws 转换为 wss 的过程是什么?

wss 是通过普通 HTTP 进行升级还是 wss 仅适用于 HTTPS?

webSocket = new WebSocket("ws://localhost:port/Esv/ocp");

工作正常,当我将 ws 更改为 wss

webSocket = new WebSocket("wss://localhost:port/Esv/ocp");

显示此错误:

Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR

简短版

是否启用 SSL

您可能有 . The connection point rule can be summarized as:

  • wsshttps only
  • 上连接
  • wshttp
  • 上连接

反之亦然:

  • https 接受 wss only
  • http 接受 ws only

错误

以下情况会导致错误(在 Firefox 下测试):

  • 如果要将 wss 连接连接到 http 端点。在我的测试中,我有一个

    InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

  • 如果要将 ws 连接连接到 https 端点,则会出现错误

    SecurityError: The operation is insecure.

正式回答

websocket的宝典是RFC 6455. In section 4.1.5:

If /secure/ is true, the client MUST perform a TLS handshake over the connection after opening the connection and before sending the handshake data [RFC2818]. If this fails (e.g., the server's certificate could not be verified), then the client MUST Fail the WebSocket Connection and abort the connection. Otherwise, all further communication on this channel MUST run through the encrypted tunnel [RFC5246].

secure 标志由 URI 定义。第 3 节定义什么是 secure

The URI is called "secure" (and it is said that "the secure flag is set") if the scheme component matches "wss" case-insensitively.


TL;DR

如果你想使用wss:

  • 您必须激活 SSL
  • 您的端点必须受到保护 (https://...):不允许“安全降级”

如果你想使用ws:

  • 确保您的端点未启用 SSL (http://...)