E
E
Eugene2019-01-07 18:51:30
Android
Eugene, 2019-01-07 18:51:30

WebSocket server C# - WebSocket client Unity: connection fails with error 1006?

Good afternoon!
Experimenting with sockets in unity. When you try to establish a connection, it opens and immediately closes
Client

spoiler
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using WebSocketSharp;

public class websocket : MonoBehaviour {
    private WebSocket ws;
    EventArgs e;
    // Use this for initialization
    void Awake () {
        ws = new WebSocket("ws://127.0.0.1:8002","Tcp");
        ws.OnOpen += OnOpenHandler;
        ws.OnError += OnErrorHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OncloseHandler;
    }
  
  // Update is called once per frame
  void Update () {
    
  }
    public void send()
    {
        ws.Send("11");
    }

    public void conn()
    {
        ws.Connect();
    }

    public void close()
    {
        ws.Close();
    }

    private void OnOpenHandler(object sender, System.EventArgs e)
    {
        Debug.Log("WebSocket connected!");
    }
    private void OnErrorHandler(object sender, WebSocketSharp.ErrorEventArgs e)
    {

        Debug.Log(e.Message);
    }
    private void OncloseHandler(object sender, WebSocketSharp.CloseEventArgs e)
    {

        Debug.Log(e.Code);
    }
    private void OnMessageHandler(object sender, WebSocketSharp.MessageEventArgs e)
    {

        if (e.IsText)
        {
  // Do something with e.Data.
        Debug.Log(e.Data);
        }


        if (e.IsBinary)
        {
  // Do something with e.RawData.
        
        Debug.Log(e.RawData);
        }
    }

}


server code
spoiler
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MyTcpListener
{
    public static void Main()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 13000.
            Int32 port = 8002;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent: {0}", data);
                }

                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
}

when trying to connect, it gives the end code 1006 in unity
Help, what could be the reason.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shai_hulud, 2019-01-07
@Genya24

The reason is that it is not a web socket that is not listening from the server.
Web sockets are not TCP sockets.
https://en.wikipedia.org/wiki/WebSocket
Also WebSocketSharp is a buggy one that breaks on iOS and Android when the application is minimized/maximized. In production it is better to use BestHttp

B
Bycufal, 2020-03-11
@Bycufal

WebSocket does not work on TCP. And yes. WebSocketSharp library is very buggy. But there is also a server. In addition, you still need to solve the problem with certificates on the server side, so you just won’t connect.
server

private static void InsertCertificate(WebSocketServer server)
        {
            var certificate = $"{Application.streamingAssetsPath}/certificate.pfx";
            server.SslConfiguration.ServerCertificate = new X509Certificate2(certificate);
        }

client:
public class CertificateCtrl
    {
        public CertificateCtrl()
        {
            ServicePointManager.CertificatePolicy = new StubCertificatePolicy();
            ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
                {
                    var isOk = true;
                    // If there are errors in the certificate chain, look at each error to determine the cause.
                    if (sslPolicyErrors == SslPolicyErrors.None) 
                        return isOk;
                    
                    foreach (var t in chain.ChainStatus)
                    {
                        if (t.Status == X509ChainStatusFlags.RevocationStatusUnknown) 
                            continue;
                            
                        chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                        chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                        chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                        chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                        var chainIsValid = chain.Build((X509Certificate2) certificate);
                        Debug.Log($"ChainIsValid: {chainIsValid}");
                        if (!chainIsValid)
                            isOk = false;
                    }

                    return isOk;
                };
        }
        
        private enum CertificateProblem : uint
        {
            None = 0x00000000,
            CertExpired = 0x800B0101,
            CertValidityPeriodNesting = 0x800B0102,
            CertRole = 0x800B0103,
            CertPathLenConst = 0x800B0104,
            CertCritical = 0x800B0105,
            CertPurpose = 0x800B0106,
            CertIssuerChaining = 0x800B0107,
            CertMalformed = 0x800B0108,
            CertUntrustedRoot = 0x800B0109,
            CertChaining = 0x800B010A,
            CertRevoked = 0x800B010C,
            CertUntrustedTestRoot = 0x800B010D,
            CertRevocationFailure = 0x800B010E,
            CertCnNoMatch = 0x800B010F,
            CertWrongUsage = 0x800B0110,
            CertUntrustedCa = 0x800B0112,

            //https://docs.microsoft.com/ru-ru/office/troubleshoot/error-messages/generic-trust-failure-(0x800b010b)-error
            GeneralFailureOfTrust = 0x800B010B
        };
        
        private class StubCertificatePolicy : ICertificatePolicy
        {
            private const bool DefaultValidate = true;

            public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request,
                int certificateProblem)
            {
                if ((CertificateProblem) certificateProblem != CertificateProblem.None)
                {
                    Debug.Log($"Certificate Problem with accessing {request?.RequestUri}");
                    Debug.Log($"Problem code 0x{certificateProblem:X8},");
                    Debug.LogError(GetProblemMessage((CertificateProblem) certificateProblem));
                    return true;
                }

                return DefaultValidate;
            }

            private static string GetProblemMessage(CertificateProblem problem)
            {
                var problemMessage = string.Empty;
                var problemCodeName = Enum.GetName(typeof(CertificateProblem), problem);
                problemMessage = !string.IsNullOrEmpty(problemCodeName)
                    ? $"{problemMessage} Certificate problem:{problem}  code:{problemCodeName}"
                    : "Unknown Certificate Problem";

                return problemMessage;
            }
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question