Wss 和 wss 的区别?

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

Wss 是通过普通 HTTP 进行升级还是只能通过 HTTPS 进行升级?

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

当我把 ws 改成 wss 的时候,工作的很好

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

它显示了这个错误:

连接建立错误: net: : ERR _ SSL _ PROTOCOL _ ERROR

70310 次浏览

Short version

To SSL or not SSL

You may have a SSL certificate issue. The connection point rule can be summarized as:

  • wss connects on https only
  • ws connects on http

and vice-versa:

  • https accepts wss only
  • http accepts ws only

Errors

Following situations will lead you to an error (tests done under Firefox):

  • If you want to connect a wss connection to a http endpoint. In my tests, I had an

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

  • If you want to connect a ws connection to a https endpoint, you'll have the error

    SecurityError: The operation is insecure.

Formal answer

The bible of websocket is 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].

The secure flag is defined by the URI. Section 3 defines what is 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

If you want to use wss:

  • you must have SSL activated
  • your endpoint point must be secured (https://...): "security downgrade" is not allowed

If you want to use ws:

  • Make sure your endpoint does not have SSL enabled (http://...)