Reputation: 510
I created an HTTPS
web server using Node.js
and a socket server using WebSocket
.
Both servers use the same 443
port.
For the web client, I was able to connect to the websocket server normally through the code below.
const ws = new WebSocket('wss://localhost/');
ws.onopen = () => {
console.info(`WebSocket server and client connection`);
ws.send('Data');
};
However, the websocket client code in Unity
as shown below causes an error.
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.
Is the Unity client unable to connect by inserting a Self-Signed Certificate (SSC)
to configure HTTPS
?
If you change to HTTP
and set the port number to 80
, it's confirmed that the Unity client is also connected normally.
If it's an SSL
issue, how do I fix the code to enable communication?
Upvotes: 2
Views: 3721
Reputation: 510
I found a solution to the above issue.
The code below performs the process of connecting to the WebSocket
server inside the web server from the Unity client
.
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");
}
}
}
Upvotes: 4