endel / NativeWebSocket

🔌 WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP)
Other
1.13k stars 155 forks source link

Secure Websockets Support #38

Open davidpmontesNASA opened 3 years ago

davidpmontesNASA commented 3 years ago

Is connection to a secure websocket supported?

studentutu commented 3 years ago

@davidpmontesNASA tested for wss:// + Tls - yes for UWP, Standalone, Android (probably IOS also), haven't checked the WebGL for it

baek-eng commented 2 years ago

Can you share how you checked for the TLS support?

I am also trying to write a websocket client to my backend server (which uses TLS).

studentutu commented 2 years ago

@baek-eng

changed a bit to allow custom requestedSubProtocols :

namespace UnityWebSocket
{
    public class SocketOptions
    {
        private readonly IList<string> requestedSubProtocols;
        private readonly WebHeaderCollection requestHeaders;
        private TimeSpan keepAliveInterval;
        private int receiveBufferSize;
        private int sendBufferSize;

        public WebHeaderCollection RequestHeaders => this.requestHeaders;
        public int ReceiveBufferSize => this.receiveBufferSize;
        public int SendBufferSize => this.sendBufferSize;
        public IList<string> RequestedSubProtocols => this.requestedSubProtocols;

        public TimeSpan KeepAliveInterval
        {
            get => this.keepAliveInterval;
            set { this.keepAliveInterval = value; }
        }

        public SocketOptions()
        {
            this.requestHeaders = new WebHeaderCollection();
            this.requestedSubProtocols = (IList<string>) new List<string>();
            this.receiveBufferSize = 16384;
            this.sendBufferSize = 16384;
            this.keepAliveInterval = System.Net.WebSockets.WebSocket.DefaultKeepAliveInterval;
        }

        public void SetRequestHeader(string headerName, string headerValue)
        {
            this.requestHeaders.Set(headerName, headerValue);
        }

        public void SetBuffer(int receiveBufferSize, int sendBufferSize)
        {
            this.receiveBufferSize = receiveBufferSize;
            this.sendBufferSize = sendBufferSize;
        }

        public void AddSubProtocol(string subProtocol)
        {
            this.requestedSubProtocols.Add(subProtocol);
        }
    }
}
    public enum WebSocketProtocols
    {
        None,
        Ssl2, // 0x0000000C
        Ssl3, // 0x00000030
        Tls, // 0x000000C0
        Tls11, // 0x00000300
        Tls12, // 0x00000C00
        Tls13, // 0x00003000
        // Default = Tls | Ssl3,
    }

Usage :

            _ws = new UnityWebSocket.Uniform.WebSocket(_targetUrl);
            var getOptions = new SocketOptions();
            getOptions.AddSubProtocol(WebSocketProtocols.Tls.ToString());
            getOptions.KeepAliveInterval = TimeSpan.FromMinutes(2);
            _ws.SetOptions(getOptions);