How to implement WebSocketSharp Unity Client with SSL/TLS connection that has to be connected to Node.js Server?

123 views Asked by At

Following is my simple Node.js server.

const { createServer } = require('https');
const { WebSocketServer, createWebSocketStream } = require('ws');
const { readFileSync } = require('fs');
const server = createServer({
    cert: readFileSync('certs/x509.crt'),
    key: readFileSync('certs/x509.key')
});

const wss = new WebSocketServer({ server });

wss.on('connection', (ws) => {
    console.log('One client has connected.');
    ws.on('message', (data) => {
        console.log('data received: %s', data);
        ws.send(data.toString());
    })
    ws.on('close', () => {
        console.log('One client has disconnected.');
    })
})

server.listen(8080, '127.0.0.1', () => {
    console.log(`Server HTTPS WS launched 127.0.0.1:${ 8080}`)
}); 

my node.js folder includes the certs folder. In Godot Engine, it succeeded when using WebSocketPeer, X509Certificate, and StreamPeerBuffer. But when it comes to Unity... Following is my simple Unity's NetworkClient.cs file content.

using System.Collections;
using System.Collections.Generic;
using WebSocketSharp;
using WebSocketSharp.Net;
using UnityEngine;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.ConstrainedExecution;
using System;

public class NetworkClient : MonoBehaviour
{
    // Start is called before the first frame update
    WebSocket ws;
    void Start()
    {
        var cert = new X509Certificate2("Assets/Certs/x509.crt");
        var sslConfig = new ClientSslConfiguration("localhost");
        var ws = new WebSocket("wss://localhost:8080");
        ws.OnMessage += (sender, e) => 
        {
            Debug.Log("Message received from " + ((WebSocket)sender).Url + " Data : " + e.Data);
        };
        ws.Connect();
    }

    // Update is called once per frame
    void Update()
    {
        if (ws == null)
        {
            return;    
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ws.Send("Hello");
        }
    }
}

I know that this wasn't even an implementation of TLS, but then how should I establish an SSL/TLS connection? I am new to network programming, especially with Unity, and I couldn't find a related FAQ on the Internet.

I expected a "Hello" sent to the server and echo a "Hello" when the space key is pressed. The connection is established over SSL/TLS.

0

There are 0 answers