我使用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
问题,如何修复代码以启用通信?
我找到了上述问题的解决方案。
下面的代码执行从Unity client
连接到web服务器内部的WebSocket
服务器的过程。
客户端.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");
}
}
}