@Genya24

WebSocket server C# — WebSocket client Unity: соединение завершается с ошибкой 1006?

Добрый день!

Эксперементирую с сокетами в unity. При попытке установить соединение, оно открывается и сразу закрывается

Клиент
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);
        }
    }

}



код сервера

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();
    }
}


при попытке соединения выдает в unity код завершения 1006

Помогите , в чем может быть причина.
  • Вопрос задан
  • 3992 просмотра
Решения вопроса 1
shai_hulud
@shai_hulud
Причина в том что с сервера не слушается не веб-сокет.
Веб сокеты это не TCP сокеты.

https://en.wikipedia.org/wiki/WebSocket

Еще WebSocketSharp глючная либа, которая ломается на iOS и Android когда приложение сворачивается/разворачивается. В продакшене лучше использовать BestHttp
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Bycufal
WebSocket не работает на TCP. И да. WebSocketSharp библиотека очень глючная. Но там и сервер есть. К тому же, нужно еще решить проблему с сертифиактами на стороне сервера, так просто вы не подключитесь.
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;
            }
        }
    }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы