Unity如何连接基于Node.js的Secure WebSocket?

How can Unity connect with Secure WebSocket based on Node.js?

我使用 Node.js 创建了一个 HTTPS 网络服务器,使用 WebSocket 创建了一个套接字服务器。

两台服务器使用相同的 443 端口。

对于web客户端,我可以通过下面的代码正常连接到websocket服务器。

const ws = new WebSocket('wss://localhost/');
ws.onopen = () => {
  console.info(`WebSocket server and client connection`);

  ws.send('Data');
};

然而,如下所示Unity中的websocket客户端代码导致错误。

using WebSocketSharp;

...
private WebSocket _ws;

void Start()
{
  _ws = new WebSocket("wss://localhost/");
  _ws.Connect();
  _ws.OnMessage += (sender, e) =>
  {
    Debug.Log($"Received {e.Data} from server");
    Debug.Log($"Sender: {((WebSocket)sender).Url}");
  };
}

void Update()
{
  if(_ws == null)
  {
    return;
  }

  if(Input.GetKeyDown(KeyCode.Space))
  {
    _ws.Send("Hello");
  }
}

InvalidOperationException: The current state of the connection is not Open.

Unity客户端是不是插个Self-Signed Certificate (SSC)配置HTTPS连接不上?

如果改为HTTP,端口号设置为80,则确认Unity客户端也连接正常

如果是 SSL 问题,我该如何修复代码以启用通信?

我找到了解决上述问题的方法。

下面的代码执行从 Unity client.

连接到 Web 服务器内部的 WebSocket 服务器的过程

client.cs

using UnityEngine;
using WebSocketSharp;

public class client : MonoBehaviour
{
     private WebSocket _ws;
     
     private void Start()
     {
          _ws = new WebSocket("wss://localhost/");
          _ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
          
          Debug.Log("Initial State : " + _ws.ReadyState);

          _ws.Connect();
          _ws.OnMessage += (sender, e) =>
          {
               Debug.Log($"Received {e.Data} from " + ((WebSocket)sender).Url + "");
          };
     }

     private void Update()
     {
         if(_ws == null) 
         {
              return;
         }

         if(Input.GetKeyDown(KeyCode.Space))
         {
              _ws.Send("Unity data");
         }
     }
}