【问题标题】:How can Unity connect with Secure WebSocket based on Node.js?Unity 如何连接基于 Node.js 的 Secure WebSocket?
【发布时间】:2021-07-06 09:40:00
【问题描述】:

我使用Node.js 创建了一个HTTPS Web 服务器,并使用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:连接的当前状态不是 Open。​​

Unity客户端是否无法通过插入Self-Signed Certificate (SSC)来配置HTTPS进行连接?

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

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

【问题讨论】:

    标签: unity3d ssl websocket https


    【解决方案1】:

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

    下面的代码执行从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");
             }
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2014-07-26
      • 2011-08-11
      • 2021-06-26
      相关资源
      最近更新 更多