private IEnumerator Send(string json, List <string> attachments, BacktraceReport report, Action <BacktraceResult> callback)
        {
            using (var request = new UnityWebRequest(_serverurl, "POST"))
            {
                AppendBodyToFile(json);
                byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
                request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                request.SetRequestHeader("Content-Type", "application/json");
                yield return(request.SendWebRequest());

                BacktraceResult result;
                if (request.responseCode == 200)
                {
                    result = new BacktraceResult();
                    OnServerResponse?.Invoke(result);
                    var response = BacktraceResult.FromJson(request.downloadHandler.text);
                    if (attachments != null && attachments.Count > 0)
                    {
                        var stack = new Stack <string>(attachments);
                        yield return(SendAttachment(response.Object, stack));
                    }
                }
                else
                {
                    PrintLog(request);
                    var exception = new Exception(request.error);
                    result = BacktraceResult.OnError(report, exception);
                    OnServerError?.Invoke(exception);
                }
                callback?.Invoke(result);
                yield return(result);
            }
        }
        void InitServer()
        {
            recipientsCache = new List <int> [transports.Length];

            // wire all the base transports to my events
            for (int i = 0; i < transports.Length; i++)
            {
                recipientsCache[i] = new List <int>();

                // this is required for the handlers,  if I use i directly
                // then all the handlers will use the last i
                int       locali    = i;
                Transport transport = transports[i];

                transport.OnServerConnected.AddListener(baseConnectionId =>
                {
                    OnServerConnected.Invoke(FromBaseId(locali, baseConnectionId));
                });

                transport.OnServerDataReceived.AddListener((baseConnectionId, data, channel) =>
                {
                    OnServerDataReceived.Invoke(FromBaseId(locali, baseConnectionId), data, channel);
                });

                transport.OnServerError.AddListener((baseConnectionId, error) =>
                {
                    OnServerError.Invoke(FromBaseId(locali, baseConnectionId), error);
                });
                transport.OnServerDisconnected.AddListener(baseConnectionId =>
                {
                    OnServerDisconnected.Invoke(FromBaseId(locali, baseConnectionId));
                });
            }
        }
Example #3
0
        void AddServerCallbacks()
        {
            // wire all the base transports to my events
            for (int i = 0; i < transports.Length; i++)
            {
                // this is required for the handlers,  if I use i directly
                // then all the handlers will use the last i
                int       locali    = i;
                Transport transport = transports[i];

                transport.OnServerConnected = (baseConnectionId =>
                {
                    OnServerConnected.Invoke(FromBaseId(locali, baseConnectionId));
                });

                transport.OnServerDataReceived = (baseConnectionId, data, channel) =>
                {
                    OnServerDataReceived.Invoke(FromBaseId(locali, baseConnectionId), data, channel);
                };

                transport.OnServerError = (baseConnectionId, error) =>
                {
                    OnServerError.Invoke(FromBaseId(locali, baseConnectionId), error);
                };
                transport.OnServerDisconnected = baseConnectionId =>
                {
                    OnServerDisconnected.Invoke(FromBaseId(locali, baseConnectionId));
                };
            }
        }
Example #4
0
        private void ConnectCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;

            try
            {
                // Complete the connection.
                socket.EndConnect(ar);
                clientConnected = true;
                Log.Verbose("Socket connected to {0}", socket.RemoteEndPoint.ToString());

                OnServerConnected?.Invoke(this, new ServerConnectedArgs(socket));

                socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
            }
            catch (ObjectDisposedException exception)
            {
                Log.Verbose(exception, "ConnectCallback");
            }
            catch (SocketException socketException)
            {
                Log.Verbose("Pool connection error", socketException);
                OnServerError?.Invoke(this, new ServerErrorArgs(socketException, socket));
            }
        }
        private void RegisterMirrorEvents()
        {
            // Server
            _svConnected    = (id) => OnServerConnected?.Invoke(id);
            _svDisconnected = (id) => OnServerDisconnected?.Invoke(id);
            _svDataReceived = (id, data) => OnServerDataReceived?.Invoke(id, new ArraySegment <byte>(data));
            _svError        = (id, exception) => OnServerError?.Invoke(id, exception);

            Server.OnConnected    += _svConnected;
            Server.OnDisconnected += _svDisconnected;
            Server.OnDataReceived += _svDataReceived;
            Server.OnError        += _svError;

            // Client
            _clConnected    = () => OnClientConnected?.Invoke();
            _clDisconnected = () => OnClientDisconnected?.Invoke();
            _clDataReceived = (data) => OnClientDataReceived?.Invoke(new ArraySegment <byte>(data));
            _clError        = (exception) => OnClientError?.Invoke(exception);

            Client.OnConnected    += _clConnected;
            Client.OnDisconnected += _clDisconnected;
            Client.OnDataReceived += _clDataReceived;
            Client.OnError        += _clError;

            _eventsRegistered = true;
        }
Example #6
0
        public WebsocketTransport()
        {
            // dispatch the events from the server
            server.Connected     += (connectionId) => OnServerConnected.Invoke(connectionId);
            server.Disconnected  += (connectionId) => OnServerDisconnected.Invoke(connectionId);
            server.ReceivedData  += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, data);
            server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error);

            // dispatch events from the client
            client.Connected     += () => OnClientConnected.Invoke();
            client.Disconnected  += () => OnClientDisconnected.Invoke();
            client.ReceivedData  += (data) => OnClientDataReceived.Invoke(data);
            client.ReceivedError += (error) => OnClientError.Invoke(error);

            // configure
            client.NoDelay = NoDelay;
            server.NoDelay = NoDelay;

            // HLAPI's local connection uses hard coded connectionId '0', so we
            // need to make sure that external connections always start at '1'
            // by simple eating the first one before the server starts
            Server.NextConnectionId();

            Debug.Log("Websocket transport initialized!");
        }
Example #7
0
        private BacktraceResult Send(Guid requestId, string json, List <string> attachments, BacktraceReport report, int deduplication = 0)
        {
            var requestUrl = _serverurl.ToString();

            if (deduplication > 0)
            {
                requestUrl += $"&_mod_duplicate={deduplication}";
            }

            var    formData    = FormDataHelper.GetFormData(json, attachments, requestId);
            string contentType = FormDataHelper.GetContentTypeWithBoundary(requestId);
            var    request     = WebRequest.Create(requestUrl) as HttpWebRequest;

            //Set up the request properties.
            request.Method        = "POST";
            request.ContentType   = contentType;
            request.ContentLength = formData.Length;
            try
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(formData, 0, formData.Length);
                    requestStream.Close();
                }
                return(ReadServerResponse(request, report));
            }
            catch (Exception exception)
            {
                OnServerError?.Invoke(exception);
                return(BacktraceResult.OnError(report, exception));
            }
#endif
        }
Example #8
0
        public bool ProcessServerMessage()
        {
            if (serverHostId == -1)
            {
                return(false);
            }

            int connectionId = -1;
            int channel;
            int receivedSize;
            NetworkEventType networkEvent = NetworkTransport.ReceiveFromHost(serverHostId, out connectionId, out channel, serverReceiveBuffer, serverReceiveBuffer.Length, out receivedSize, out error);

            // note: 'error' is used for extra information, e.g. the reason for
            // a disconnect. we don't necessarily have to throw an error if
            // error != 0. but let's log it for easier debugging.
            //
            // DO NOT return after error != 0. otherwise Disconnect won't be
            // registered.
            NetworkError networkError = (NetworkError)error;

            if (networkError != NetworkError.Ok)
            {
                string message = "NetworkTransport.Receive failed: hostid=" + serverHostId + " connId=" + connectionId + " channelId=" + channel + " error=" + networkError;

                // TODO write a TransportException or better
                OnServerError.Invoke(connectionId, new Exception(message));
            }

            // LLAPI client sends keep alive messages (75-6C-6C) on channel=110.
            // ignore all messages that aren't for our selected channel.

            /*if (channel != channelId)
             * {
             *  return false;
             * }*/

            switch (networkEvent)
            {
            case NetworkEventType.ConnectEvent:
                OnServerConnected.Invoke(connectionId);
                break;

            case NetworkEventType.DataEvent:
                byte[] data = new byte[receivedSize];
                Array.Copy(serverReceiveBuffer, data, receivedSize);
                OnServerDataReceived.Invoke(connectionId, data);
                break;

            case NetworkEventType.DisconnectEvent:
                OnServerDisconnected.Invoke(connectionId);
                break;

            default:
                // nothing or a message we don't recognize
                return(false);
            }

            return(true);
        }
Example #9
0
        private IEnumerator Send(string json, List <string> attachments, BacktraceReport report, int deduplication, Action <BacktraceResult> callback)
        {
            var requestUrl = _serverurl.ToString();

            if (deduplication > 0)
            {
                var startingChar = string.IsNullOrEmpty(_serverurl.Query) ? "?" : "&";
                requestUrl += string.Format("{0}_mod_duplicate={1}", startingChar, deduplication);
            }
            using (var request = new UnityWebRequest(requestUrl, "POST"))
            {
#if UNITY_2018_4_OR_NEWER
                if (_ignoreSslValidation)
                {
                    request.certificateHandler = new BacktraceSelfSSLCertificateHandler();
                }
#endif

                byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
                request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                request.SetRequestHeader("Content-Type", "application/json");
                yield return(request.SendWebRequest());

                BacktraceResult result;
                if (request.responseCode == 200)
                {
                    result = new BacktraceResult();
                    if (OnServerResponse != null)
                    {
                        OnServerResponse.Invoke(result);
                    }
                    var response = BacktraceResult.FromJson(request.downloadHandler.text);
                    if (attachments != null && attachments.Count > 0)
                    {
                        var stack = new Stack <string>(attachments);
                        yield return(SendAttachment(response.RxId, stack));
                    }
                }
                else
                {
                    PrintLog(request);
                    var exception = new Exception(request.error);
                    result = BacktraceResult.OnError(report, exception);
                    if (OnServerError != null)
                    {
                        OnServerError.Invoke(exception);
                    }
                }

                if (callback != null)
                {
                    callback.Invoke(result);
                }
                yield return(result);
            }
        }
Example #10
0
File: Monke.cs Project: dededec/TFG
    private void SetupCallbacks()
    {
        CommunicationTransport.OnServerConnected    = OnServerConnect;
        CommunicationTransport.OnServerDisconnected = OnServerDisconnect;
        CommunicationTransport.OnServerDataReceived = OnServerDataReceive;
        CommunicationTransport.OnServerError        = (i, e) => OnServerError?.Invoke(i, e);

        CommunicationTransport.OnClientDataReceived = OnClientDataReceive;
        CommunicationTransport.OnClientDisconnected = () => OnClientDisconnected?.Invoke();
        CommunicationTransport.OnClientError        = (e) => OnClientError?.Invoke(e);
    }
Example #11
0
        public SteamworksTransport()
        {
            _client = new P2PClient();
            _server = new P2PServer();

            _client.OnConnected.AddListener(() => OnClientConnected?.Invoke());
            _client.OnData.AddListener(bytes => { OnClientDataReceived?.Invoke(bytes); });
            _client.OnError.AddListener(exception => { OnClientError?.Invoke(exception); });
            _client.OnDisconnect.AddListener(() => { OnClientDisconnected?.Invoke(); });

            _server.OnConnect.AddListener(id => { OnServerConnected?.Invoke(id); });
            _server.OnData.AddListener((id, data) => { OnServerDataReceived?.Invoke(id, data); });
            _server.OnError.AddListener((id, exception) => { OnServerError?.Invoke(id, exception); });
            _server.OnDisconnect.AddListener(id => { OnServerDisconnected?.Invoke(id); });
        }
Example #12
0
        internal async Task <BacktraceResult> SendAsync(Guid requestId, string json, List <string> attachments, BacktraceReport report, int deduplication = 0)
        {
            string contentType = FormDataHelper.GetContentTypeWithBoundary(requestId);
            string boundary    = FormDataHelper.GetBoundary(requestId);

            using (var content = new MultipartFormDataContent(boundary))
            {
                var requestUrl = _serverurl.ToString();
                if (deduplication > 0)
                {
                    requestUrl += $"&_mod_duplicate={deduplication}";
                }

                var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                content.AddJson("upload_file.json", json);
                content.AddFiles(attachments);

                //// clear and add content type with boundary tag
                content.Headers.Remove("Content-Type");
                content.Headers.TryAddWithoutValidation("Content-Type", contentType);
                request.Content = content;
                try
                {
                    using (var response = await HttpClient.SendAsync(request))
                    {
                        var fullResponse = await response.Content.ReadAsStringAsync();

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            var err = new WebException(response.ReasonPhrase);
                            System.Diagnostics.Trace.WriteLine(fullResponse);
                            OnServerError?.Invoke(err);
                            return(BacktraceResult.OnError(report, err));
                        }
                        var result = JsonConvert.DeserializeObject <BacktraceResult>(fullResponse);
                        result.BacktraceReport = report;
                        OnServerResponse?.Invoke(result);
                        return(result);
                    }
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Trace.WriteLine($"Backtrace - Server error: {exception.ToString()}");
                    OnServerError?.Invoke(exception);
                    return(BacktraceResult.OnError(report, exception));
                }
            }
        }
        public FizzySteamyMirror()
        {
            // dispatch the events from the server
            server.OnConnected     += (id) => OnServerConnected?.Invoke(id);
            server.OnDisconnected  += (id) => OnServerDisconnected?.Invoke(id);
            server.OnReceivedData  += (id, data, channel) => OnServerDataReceived?.Invoke(id, new ArraySegment <byte>(data), channel);
            server.OnReceivedError += (id, exception) => OnServerError?.Invoke(id, exception);

            // dispatch events from the client
            client.OnConnected     += () => OnClientConnected?.Invoke();
            client.OnDisconnected  += () => OnClientDisconnected?.Invoke();
            client.OnReceivedData  += (data, channel) => OnClientDataReceived?.Invoke(new ArraySegment <byte>(data), channel);
            client.OnReceivedError += (exception) => OnClientError?.Invoke(exception);

            Debug.Log("FizzySteamyMirror initialized!");
        }
        public WebsocketTransport()
        {
            // dispatch the events from the server
            server.Connected     += (connectionId) => OnServerConnected.Invoke(connectionId);
            server.Disconnected  += (connectionId) => OnServerDisconnected.Invoke(connectionId);
            server.ReceivedData  += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, data, Channels.DefaultReliable);
            server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error);

            // dispatch events from the client
            client.Connected     += () => OnClientConnected.Invoke();
            client.Disconnected  += () => OnClientDisconnected.Invoke();
            client.ReceivedData  += (data) => OnClientDataReceived.Invoke(data, Channels.DefaultReliable);
            client.ReceivedError += (error) => OnClientError.Invoke(error);

            // configure
            client.NoDelay = NoDelay;
            server.NoDelay = NoDelay;
        }
Example #15
0
        public override bool ServerSend(List <int> connectionIds, int channelId, ArraySegment <byte> segment)
        {
            bool failed = false;

            for (int i = 0; i < connectionIds.Count; i++)
            {
                try
                {
                    lobbyManager.SendNetworkMessage(currentLobby.Id, clients.GetBySecond(connectionIds[i]), (byte)channelId, segment.Array);
                }
                catch (Exception e)
                {
                    OnServerError?.Invoke(connectionIds[i], new Exception("Error sending data to client: " + e.ToString()));
                    failed = true;
                }
            }
            return(!failed);
        }
        void LobbyCreated(Result result, ref Lobby lobby)
        {
            lobbyCreated = true;
            switch (result)
            {
            case (Result.Ok):
                currentLobby = lobby;
                lobbyManager.ConnectNetwork(currentLobby.Id);
                lobbyManager.OpenNetworkChannel(currentLobby.Id, 0, true);
                lobbyManager.OpenNetworkChannel(currentLobby.Id, 1, false);
                break;

            default:
                OnServerError?.Invoke(0, new Exception("Failed to start discord lobby, Reason: " + result));
                Debug.LogError("Discord Transport - ERROR: " + result.ToString());
                break;
            }
        }
Example #17
0
        public void Awake()
        {
            // dispatch the events from the server
            server.Connected     += (connectionId) => OnServerConnected.Invoke(connectionId);
            server.Disconnected  += (connectionId) => OnServerDisconnected.Invoke(connectionId);
            server.ReceivedData  += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, new ArraySegment <byte>(data), Channels.DefaultReliable);
            server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error);

            // dispatch events from the client
            client.Connected     += () => OnClientConnected.Invoke();
            client.Disconnected  += () => OnClientDisconnected.Invoke();
            client.ReceivedData  += (data) => OnClientDataReceived.Invoke(new ArraySegment <byte>(data), Channels.DefaultReliable);
            client.ReceivedError += (error) => OnClientError.Invoke(error);

            // configure
            client.NoDelay = NoDelay;
            server.NoDelay = NoDelay;

            Debug.Log("Tcp transport initialized!");
        }
        public WebsocketTransport()
        {
            // dispatch the events from the server
            server.Connected     += (connectionId) => OnServerConnected.Invoke(connectionId);
            server.Disconnected  += (connectionId) => OnServerDisconnected.Invoke(connectionId);
            server.ReceivedData  += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, data);
            server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error);

            // dispatch events from the client
            client.Connected     += () => OnClientConnected.Invoke();
            client.Disconnected  += () => OnClientDisconnected.Invoke();
            client.ReceivedData  += (data) => OnClientDataReceived.Invoke(data);
            client.ReceivedError += (error) => OnClientError.Invoke(error);

            // configure
            client.NoDelay = NoDelay;
            server.NoDelay = NoDelay;

            Debug.Log("Websocket transport initialized!");
        }
Example #19
0
        private void FixedUpdate()
        {
            if (_server.Listening)
            {
                if (_timeouts == null)
                {
                    return;
                }
                foreach (var client in _timeouts)
                {
                    if (client.Value < TimeoutSeconds)
                    {
                        continue;
                    }

                    if (!GetServerConnectionMap().TryGetByFirst(client.Key, out var clientID))
                    {
                        OnServerError?.Invoke(-1, new SteamConnectionException("Tried to timeout an unmapped client."));
                        _timeouts.Remove(client.Key);
                        return;
                    }

                    OnServerError?.Invoke(clientID, new ConnectionTimeoutException($"Connection to {client.Key} timed out."));
                    ServerDisconnect(clientID);
                    _timeouts.Remove(client.Key);
                    return;
                }
            }
            else if (_client.Connected)
            {
                var host = _timeouts.First();

                if (host.Value < TimeoutSeconds)
                {
                    return;
                }

                OnClientError?.Invoke(new ConnectionTimeoutException("Connection to host timed out."));
                ClientDisconnect();
            }
        }
Example #20
0
        private void Receive(Socket socket)
        {
            if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
            {
                return;
            }

            try
            {
                // Begin receiving the data from the remote device.
                socket.BeginReceive(buffer, 0, BUFFER_SIZE, 0,
                                    new AsyncCallback(ReceiveCallback), socket);
            }
            catch (Exception exception)
            {
                if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
                {
                    Log.Error(exception, "Receive");
                    OnServerError?.Invoke(this, new ServerErrorArgs(exception, socket));
                }
            }
        }
Example #21
0
        public void SendToPool(byte[] data)
        {
            if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
            {
                return;
            }

            Log.Verbose("Client SendToPool: {0}", data.GetString());
            // Begin sending the data to the remote device.
            try
            {
                data = data.CheckForNewLine();

                this.clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None,
                                            new AsyncCallback(SendCallback), clientSocket);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "SendToPool");
                OnServerError?.Invoke(this, new ServerErrorArgs(ex, clientSocket));
            }
        }
Example #22
0
        private void ReceiveCallback(IAsyncResult AR)
        {
            if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
            {
                return;
            }

            Socket socket = (Socket)AR.AsyncState;
            int    received;

            try
            {
                received = socket.EndReceive(AR);
            }
            catch (ObjectDisposedException ex)
            {
                if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
                {
                    return;
                }

                Log.Debug(ex, "Client ObjectDisposed exception");
                OnServerDisconnected?.Invoke(this, new ServerDisonnectedArgs(socket));

                return;
            }
            catch (SocketException ex)
            {
                Log.Debug(ex, "Client forcefully disconnected");
                OnServerDisconnected?.Invoke(this, new ServerDisonnectedArgs(socket));

                return;
            }

            if (received == 0)
            {
                if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
                {
                    Log.Verbose("Pool receive buffer was empty; need to reconnect.. " + received);
                    OnServerDisconnected?.Invoke(this, new ServerDisonnectedArgs(socket));

                    return;
                }
                else
                {
                    return;
                }
            }

            lock (bufferLock)
            {
                byte[] packet = new byte[received];
                Array.Copy(buffer, packet, packet.Length);

                List <byte[]> packets = Arrays.ProcessBuffer(ref unusedBuffer, ref unusedBufferLength, buffer, received, "\n".GetBytes());

                for (int i = 0; i < packets.Count; i++)
                {
                    OnServerDataReceived?.Invoke(this, new ServerDataReceivedArgs(packets[i], socket));
                }
            }

            try
            {
                if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
                {
                    return;
                }
                socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
            }
            catch (ObjectDisposedException ex)
            {
                if (!clientConnected || isDisconnecting || !this.clientSocket.Connected)
                {
                    if (socket == null)
                    {
                        OnServerError?.Invoke(this, new ServerErrorArgs(ex, socket));
                    }
                    else
                    {
                        OnServerError?.Invoke(this, new ServerErrorArgs(ex, null));
                    }
                    Log.Error(ex, "Pool BeginReceive Error");
                }
                else
                {
                    return;
                }
            }
        }
        public virtual async Task <IRestResponse> RequestAsync(string path, Method method = Method.GET, object dto = null, Action <RestRequest> buildRequest = null, string contentType = null)
        {
            try
            {
                Log($"Request: [/{path}] {method} {path}");
                RestClient client  = CreateClient(BaseUrl);
                var        request = CreateRequest(path, method);
                buildRequest?.Invoke(request);
                if (dto != null)
                {
                    if (method == Method.GET)
                    {
                        var json = JsonConvert.SerializeObject(dto);
                        var dic  = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);
                        foreach (var pair in dic)
                        {
                            if (pair.Value != null)
                            {
                                if (!(pair.Value is string) && pair.Value is IEnumerable e)
                                {
                                    foreach (var item in e)
                                    {
                                        request.AddQueryParameter(pair.Key, item.ToString());
                                    }
                                }
                                else
                                {
                                    request.AddQueryParameter(pair.Key, pair.Value.ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        request.AddJsonBody(dto);
                    }
                }
                contentType = contentType ?? "application/json";
                request.AddHeader("Content-Type", contentType);
                request.AddHeader("Accept", contentType);
                Stopwatch watch = new Stopwatch();
                watch.Start();
                try
                {
                    var result = await client.ExecuteAsync(request);

                    OnResponse?.Invoke(this, result);
                    Log($"[{watch.Elapsed.TotalSeconds}s/{client.BaseUrl}] {request.Method} {result?.ResponseUri?.ToString() ?? path} response ({result.StatusCode}): {result.Content.Head(1024)}\n");
                    if (result.StatusCode == HttpStatusCode.Gone)
                    {
                        OnGone?.Invoke(this, result);
                        return(null);
                    }
                    if (result.StatusCode != HttpStatusCode.OK)
                    {
                        OnServerError?.Invoke(this, result);
                    }
                    OnSuccess?.Invoke(this, result);
                    return(result);
                }
                catch (Exception ex)
                {
                    Log($"Exception while executing task: {ex}");
                }
                finally
                {
                    watch.Stop();
                }
            }
            catch (Exception ex)
            {
                Log($"Exception while executing task: {ex}");
            }
            return(null);
        }
Example #24
0
        void Awake()
        {
            // logging
            //   Log.Info should use Debug.Log if enabled, or nothing otherwise
            //   (don't want to spam the console on headless servers)
            if (debugLog)
            {
                Log.Info = Debug.Log;
            }
            else
            {
                Log.Info = _ => {}
            };
            Log.Warning = Debug.LogWarning;
            Log.Error   = Debug.LogError;

#if ENABLE_IL2CPP
            // NonAlloc doesn't work with IL2CPP builds
            NonAlloc = false;
#endif

            // client
            client = NonAlloc
                ? new KcpClientNonAlloc(
                () => OnClientConnected.Invoke(),
                (message, channel) => OnClientDataReceived.Invoke(message, FromKcpChannel(channel)),
                () => OnClientDisconnected.Invoke(),
                (error, reason) => OnClientError.Invoke(ToTransportError(error), reason))
                : new KcpClient(
                () => OnClientConnected.Invoke(),
                (message, channel) => OnClientDataReceived.Invoke(message, FromKcpChannel(channel)),
                () => OnClientDisconnected.Invoke(),
                (error, reason) => OnClientError.Invoke(ToTransportError(error), reason));

            // server
            server = NonAlloc
                ? new KcpServerNonAlloc(
                (connectionId) => OnServerConnected.Invoke(connectionId),
                (connectionId, message, channel) => OnServerDataReceived.Invoke(connectionId, message, FromKcpChannel(channel)),
                (connectionId) => OnServerDisconnected.Invoke(connectionId),
                (connectionId, error, reason) => OnServerError.Invoke(connectionId, ToTransportError(error), reason),
                DualMode,
                NoDelay,
                Interval,
                FastResend,
                CongestionWindow,
                SendWindowSize,
                ReceiveWindowSize,
                Timeout,
                MaxRetransmit,
                MaximizeSendReceiveBuffersToOSLimit)
                : new KcpServer(
                (connectionId) => OnServerConnected.Invoke(connectionId),
                (connectionId, message, channel) => OnServerDataReceived.Invoke(connectionId, message, FromKcpChannel(channel)),
                (connectionId) => OnServerDisconnected.Invoke(connectionId),
                (connectionId, error, reason) => OnServerError.Invoke(connectionId, ToTransportError(error), reason),
                DualMode,
                NoDelay,
                Interval,
                FastResend,
                CongestionWindow,
                SendWindowSize,
                ReceiveWindowSize,
                Timeout,
                MaxRetransmit,
                MaximizeSendReceiveBuffersToOSLimit);

            if (statisticsLog)
            {
                InvokeRepeating(nameof(OnLogStatistics), 1, 1);
            }

            Debug.Log("KcpTransport initialized!");
        }

        void OnValidate()
        {
            // show max message sizes in inspector for convenience
            ReliableMaxMessageSize   = KcpConnection.ReliableMaxMessageSize(ReceiveWindowSize);
            UnreliableMaxMessageSize = KcpConnection.UnreliableMaxMessageSize;
        }
Example #25
0
 protected void OnServerErrorDetected(string description)
 => OnServerError?.Invoke(description);
        /// <summary>
        /// Sending diagnostic report to Backtrace
        /// </summary>
        /// <param name="json">diagnostic data JSON</param>
        /// <param name="attachments">List of report attachments</param>
        /// <param name="queryAttributes">Query string attributes</param>
        /// <param name="callback">coroutine callback</param>
        /// <returns>Server response</returns>
        public IEnumerator Send(string json, List <string> attachments, Dictionary <string, string> queryAttributes, Action <BacktraceResult> callback)
        {
            var stopWatch = EnablePerformanceStatistics
              ? System.Diagnostics.Stopwatch.StartNew()
              : new System.Diagnostics.Stopwatch();

            var requestUrl = queryAttributes != null
                ? GetParametrizedQuery(_serverUrl.ToString(), queryAttributes)
                : ServerUrl;


            List <IMultipartFormSection> formData = new List <IMultipartFormSection>
            {
                new MultipartFormFileSection("upload_file", Encoding.UTF8.GetBytes(json), "upload_file.json", "application/json")
            };

            foreach (var file in attachments)
            {
                if (File.Exists(file) && new FileInfo(file).Length < 10000000)
                {
                    formData.Add(new MultipartFormFileSection(
                                     string.Format("attachment__{0}", Path.GetFileName(file)),
                                     File.ReadAllBytes(file)));
                }
            }


            var boundaryIdBytes = UnityWebRequest.GenerateBoundary();

            using (var request = UnityWebRequest.Post(requestUrl, formData, boundaryIdBytes))
            {
#if UNITY_2018_4_OR_NEWER
                if (_ignoreSslValidation)
                {
                    request.certificateHandler = new BacktraceSelfSSLCertificateHandler();
                }
#endif
                request.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + Encoding.UTF8.GetString(boundaryIdBytes));
                request.timeout = 15000;
                yield return(request.SendWebRequest());

                BacktraceResult result;
                if (request.responseCode == 429)
                {
                    result = new BacktraceResult()
                    {
                        Message = "Server report limit reached",
                        Status  = Types.BacktraceResultStatus.LimitReached
                    };
                    if (OnServerResponse != null)
                    {
                        OnServerResponse.Invoke(result);
                    }
                }
                else if (request.responseCode == 200 && (!request.isNetworkError || !request.isHttpError))
                {
                    result = BacktraceResult.FromJson(request.downloadHandler.text);
                    _shouldDisplayFailureMessage = true;

                    if (OnServerResponse != null)
                    {
                        OnServerResponse.Invoke(result);
                    }
                }
                else
                {
                    PrintLog(request);
                    var exception = new Exception(request.error);
                    result = BacktraceResult.OnNetworkError(exception);
                    if (OnServerError != null)
                    {
                        OnServerError.Invoke(exception);
                    }
                }

                if (callback != null)
                {
                    callback.Invoke(result);
                }

                if (EnablePerformanceStatistics)
                {
                    stopWatch.Stop();
                    Debug.Log(string.Format("Backtrace - JSON send time: {0}μs", stopWatch.GetMicroseconds()));
                }
                yield return(result);
            }
        }
Example #27
0
 private void OnWsServerError(object sender, SocketErrorEventArgs e)
 {
     _logger.LogError("WebSocket [{id}] server error ({msg}): {e}", e.SessionId, e.Message, e.Error);
     OnServerError?.Invoke(sender, e);
 }
Example #28
0
 /// <summary>
 ///     Handle error notification
 /// </summary>
 /// <param name="error">Socket error code</param>
 protected virtual void OnError(SocketError error)
 {
     OnServerError?.Invoke(this, new SocketErrorEventArgs(Guid.Empty, error));
 }
Example #29
0
        /// <summary>
        /// Sending diagnostic report to Backtrace
        /// </summary>
        /// <param name="json">diagnostic data JSON</param>
        /// <param name="attachments">List of report attachments</param>
        /// <param name="queryAttributes">Query string attributes</param>
        /// <param name="callback">coroutine callback</param>
        /// <returns>Server response</returns>
        public IEnumerator Send(string json, IEnumerable <string> attachments, Dictionary <string, string> queryAttributes, Action <BacktraceResult> callback)
        {
            var stopWatch = EnablePerformanceStatistics
              ? System.Diagnostics.Stopwatch.StartNew()
              : new System.Diagnostics.Stopwatch();

            var requestUrl = queryAttributes != null
                ? GetParametrizedQuery(_serverUrl.ToString(), queryAttributes)
                : ServerUrl;

            using (var request = _httpClient.Post(requestUrl, json, attachments))
            {
                yield return(request.SendWebRequest());

                BacktraceResult result;
                if (request.responseCode == 429)
                {
                    result = new BacktraceResult()
                    {
                        Message = "Server report limit reached",
                        Status  = Types.BacktraceResultStatus.LimitReached
                    };
                    if (OnServerResponse != null)
                    {
                        OnServerResponse.Invoke(result);
                    }
                }
                else if (request.responseCode == 200 && request.ReceivedNetworkError() != true)
                {
                    result = BacktraceResult.FromJson(request.downloadHandler.text);
                    _shouldDisplayFailureMessage = true;

                    if (OnServerResponse != null)
                    {
                        OnServerResponse.Invoke(result);
                    }
                }
                else
                {
                    PrintLog(request);
                    var exception = new Exception(request.error);
                    result = BacktraceResult.OnNetworkError(exception);
                    if (OnServerError != null)
                    {
                        OnServerError.Invoke(exception);
                    }
                }

                if (callback != null)
                {
                    callback.Invoke(result);
                }

                if (EnablePerformanceStatistics)
                {
                    stopWatch.Stop();
                    Debug.Assert(EnablePerformanceStatistics, string.Format("Backtrace - JSON send time: {0}μs", stopWatch.GetMicroseconds()));
                }
                yield return(result);
            }
        }
Example #30
0
        /// <summary>
        /// Sending diagnostic report to Backtrace
        /// </summary>
        /// <param name="json">diagnostic data JSON</param>
        /// <param name="attachments">List of report attachments</param>
        /// <param name="queryAttributes">Query string attributes</param>
        /// <param name="callback">coroutine callback</param>
        /// <returns>Server response</returns>
        public IEnumerator Send(string json, List <string> attachments, Dictionary <string, string> queryAttributes, Action <BacktraceResult> callback)
        {
            var stopWatch = EnablePerformanceStatistics
              ? System.Diagnostics.Stopwatch.StartNew()
              : new System.Diagnostics.Stopwatch();

            var requestUrl = queryAttributes != null
                ? GetParametrizedQuery(_serverUrl.ToString(), queryAttributes)
                : ServerUrl;


            using (var request = new UnityWebRequest(requestUrl, "POST"))
            {
#if UNITY_2018_4_OR_NEWER
                if (_ignoreSslValidation)
                {
                    request.certificateHandler = new BacktraceSelfSSLCertificateHandler();
                }
#endif
                request.timeout = 15000;
                byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
                request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                request.SetRequestHeader("Content-Type", "application/json");
                yield return(request.SendWebRequest());

                BacktraceResult result;
                if (request.responseCode == 200)
                {
                    result = BacktraceResult.FromJson(request.downloadHandler.text);

                    if (OnServerResponse != null)
                    {
                        OnServerResponse.Invoke(result);
                    }
                    if (attachments != null && attachments.Count > 0)
                    {
                        var stack = new Stack <string>(attachments);
                        yield return(SendAttachment(result.RxId, stack));
                    }
                }
                else
                {
                    PrintLog(request);
                    var exception = new Exception(request.error);
                    result = BacktraceResult.OnError(exception);
                    if (OnServerError != null)
                    {
                        OnServerError.Invoke(exception);
                    }
                }

                if (callback != null)
                {
                    callback.Invoke(result);
                }

                if (EnablePerformanceStatistics)
                {
                    stopWatch.Stop();
                    Debug.Log(string.Format("Backtrace - JSON send time: {0}μs", stopWatch.GetMicroseconds()));
                }
                yield return(result);
            }
        }