public static async void StartToReadingClientData(ClientInfo client, ServerBase serverBase)
        {
            try
            {
                Console.WriteLine($"Stream Client Connected: {client.IPAddress}");
                PipeNetworkStream stream = client.ClientStream;
                byte firstByte           = await client.StreamHelper.ReadOneByteAsync(stream);

                if (firstByte == 0)
                {
                    await DownloadStreamFromClient(client, serverBase);
                }
                //download from server and upload from client
                else
                {
                    await UploadStreamToClient(client, serverBase);
                }
                serverBase.DisposeClient(client, null, "StartToReadingClientData finished");
            }
            catch (Exception ex)
            {
                serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase SignalGoStreamProvider StartToReadingClientData");
                serverBase.DisposeClient(client, null, "SignalGoStreamProvider StartToReadingClientData exception");
            }
        }
Esempio n. 2
0
        public static async Task AddHttpClient(HttpClientInfo client, ServerBase serverBase, string address, string methodName, IDictionary <string, string[]> requestHeaders, IDictionary <string, string[]> responseHeaders)
#endif
        {
#if (NET35 || NET40)
            return(Task.Factory.StartNew(() =>
#else
            await Task.Run(async() =>
#endif
            {
                try
                {
                    if (requestHeaders != null)
                    {
                        client.RequestHeaders = requestHeaders;
                    }
                    if (responseHeaders != null)
                    {
                        client.ResponseHeaders = responseHeaders;
                    }
                    await HandleHttpRequest(methodName, address, serverBase, client);
                }
                catch (Exception ex)
                {
                    if (client.IsOwinClient)
                    {
                        throw;
                    }
                    serverBase.DisposeClient(client, null, "HttpProvider AddHttpClient exception");
                }
            }));
        }
Esempio n. 3
0
        public static async void StartToReadingClientData(ClientInfo client, ServerBase serverBase)
        {
            //#if (NET40 || NET35)
            //            Task.Factory.StartNew(() =>
            //#else
            //            Task.Run(() =>
            //#endif
            //            {
            try
            {
                //Console.WriteLine($"OneWay Client Connected: {client.IPAddress}");
                await RunMethod(serverBase, client);

                serverBase.DisposeClient(client, null, "OneWay StartToReadingClientData finished");
            }
            catch (Exception ex)
            {
                serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase OneWay StartToReadingClientData");
                serverBase.DisposeClient(client, null, "OneWay StartToReadingClientData exception");
            }
            //});
        }
Esempio n. 4
0
        public static Task AddSignalGoWebSocketHttpClient(ClientInfo client, ServerBase serverBase)
#endif
        {
#if (NET35 || NET40)
            return(Task.Factory.StartNew(() =>
#else
            return Task.Run(async() =>
#endif
            {
                try
                {
                    client.IsWebSocket = true;
                    await SignalgoWebSocketProvider.StartToReadingClientData(client, serverBase);
                }
                catch (Exception ex)
                {
                    serverBase.DisposeClient(client, null, "HttpProvider AddWebSocketHttpClient exception");
                }
            }));
        }
        /// <summary>
        /// Exchange data from client and server
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="tcpClient"></param>
        public async void ExchangeClient(PipeNetworkStream reader, TcpClient tcpClient)
        {
            //File.WriteAllBytes("I:\\signalgotext.txt", reader.LastBytesReaded);
            ClientInfo client = null;

            try
            {
                if (_serverBase.ProviderSetting.IsEnabledToUseTimeout)
                {
                    tcpClient.GetStream().ReadTimeout  = (int)_serverBase.ProviderSetting.ReceiveDataTimeout.TotalMilliseconds;
                    tcpClient.GetStream().WriteTimeout = (int)_serverBase.ProviderSetting.SendDataTimeout.TotalMilliseconds;
                }

                string firstLineString = await reader.ReadLineAsync();

                if (firstLineString.Contains("SignalGo-Stream/4.0"))
                {
                    if (!_serverBase.ProviderSetting.IsEnabledToUseTimeout)
                    {
                        tcpClient.GetStream().ReadTimeout  = -1;
                        tcpClient.GetStream().WriteTimeout = -1;
                    }
                    client = CreateClientInfo(false, tcpClient, reader);
                    client.ProtocolType = ClientProtocolType.SignalGoStream;
                    client.StreamHelper = SignalGoStreamBase.CurrentBase;
                    SignalGoStreamProvider.StartToReadingClientData(client, _serverBase);
                }
                else if (firstLineString.Contains("SignalGo-OneWay/4.0"))
                {
                    if (!_serverBase.ProviderSetting.IsEnabledToUseTimeout)
                    {
                        tcpClient.GetStream().ReadTimeout  = -1;
                        tcpClient.GetStream().WriteTimeout = -1;
                    }
                    client = CreateClientInfo(false, tcpClient, reader);
                    client.ProtocolType = ClientProtocolType.SignalGoOneWay;
                    client.StreamHelper = SignalGoStreamBase.CurrentBase;
                    OneWayServiceProvider.StartToReadingClientData(client, _serverBase);
                }
                else if (firstLineString.Contains("SignalGo/4.0"))
                {
                    client = CreateClientInfo(false, tcpClient, reader);
                    client.ProtocolType = ClientProtocolType.SignalGoDuplex;
                    //"SignalGo/1.0";
                    client.StreamHelper = SignalGoStreamBase.CurrentBase;
                    if (_serverBase.ProviderSetting.ServerServiceSetting.IsEnabledToUseTimeout)
                    {
                        tcpClient.ReceiveTimeout = (int)_serverBase.ProviderSetting.ServerServiceSetting.ReceiveDataTimeout.TotalMilliseconds;
                        tcpClient.SendTimeout    = (int)_serverBase.ProviderSetting.ServerServiceSetting.SendDataTimeout.TotalMilliseconds;
                    }
                    else
                    {
                        tcpClient.GetStream().ReadTimeout  = -1;
                        tcpClient.GetStream().WriteTimeout = -1;
                    }
                    await SignalGoDuplexServiceProvider.StartToReadingClientData(client, _serverBase);
                }
                else if (firstLineString.Contains("HTTP/"))
                {
                    if (_serverBase.ProviderSetting.HttpSetting.IsEnabledToUseTimeout)
                    {
                        tcpClient.GetStream().ReadTimeout  = (int)_serverBase.ProviderSetting.HttpSetting.ReceiveDataTimeout.TotalMilliseconds;
                        tcpClient.GetStream().WriteTimeout = (int)_serverBase.ProviderSetting.HttpSetting.SendDataTimeout.TotalMilliseconds;
                    }
                    await HttpProvider.StartToReadingClientData(tcpClient, _serverBase, reader, new StringBuilder(firstLineString));
                }
                else
                {
                    _serverBase.DisposeClient(client, tcpClient, "AddClient header not support");
                }
            }
            catch (Exception)
            {
                _serverBase.DisposeClient(client, tcpClient, "exception");
            }
            finally
            {
                _WaitingToReadFirstLineCount--;
            }
        }
Esempio n. 6
0
        public static async Task StartToReadingClientData(ClientInfo client, ServerBase serverBase)
        {
            try
            {
                Console.WriteLine($"WebSocket Client Connected: {client.IPAddress}");
                Shared.IO.PipeNetworkStream stream = client.ClientStream;
                while (true)
                {
                    byte oneByteOfDataType = await client.StreamHelper.ReadOneByteAsync(stream);

                    //type of data
                    DataType dataType = (DataType)oneByteOfDataType;
                    if (dataType == DataType.PingPong)
                    {
                        await client.StreamHelper.WriteToStreamAsync(client.ClientStream, new byte[] { 5 });

                        continue;
                    }
                    //compress mode of data
                    CompressMode compressMode = (CompressMode)await client.StreamHelper.ReadOneByteAsync(stream);

                    //a server service method called from client
                    if (dataType == DataType.CallMethod)
                    {
                        string json = "";
                        //if (client.IsOwinClient)
                        //{
                        //    json = await stream.ReadLineAsync("#end");
                        //    if (json.EndsWith("#end"))
                        //        json = json.Substring(0, json.Length - 4);
                        //}
                        //else
                        //{
                        byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock);

                        //if (ClientsSettings.ContainsKey(client))
                        //    bytes = DecryptBytes(bytes, client);
                        json = Encoding.UTF8.GetString(bytes);
                        //}
                        MethodCallInfo callInfo = ServerSerializationHelper.Deserialize <MethodCallInfo>(json, serverBase);
                        if (callInfo.PartNumber != 0)
                        {
                            SegmentManager segmentManager = new SegmentManager();
                            ISegment       result         = segmentManager.GenerateAndMixSegments(callInfo);
                            if (result != null)
                            {
                                callInfo = (MethodCallInfo)result;
                            }
                            else
                            {
                                continue;
                            }
                        }
#if (NET35 || NET40)
                        MethodCallbackInfo callbackResult = CallMethod(callInfo, client, json, serverBase).Result;
                        SendCallbackData(callbackResult, client, serverBase);
#else
                        Task <MethodCallbackInfo> callbackResult = CallMethod(callInfo, client, json, serverBase);
                        SendCallbackData(callbackResult, client, serverBase);
#endif
                    }

                    //reponse of client method that server called to client
                    else if (dataType == DataType.ResponseCallMethod)
                    {
                        byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock);

                        //if (ClientsSettings.ContainsKey(client))
                        //    bytes = DecryptBytes(bytes, client);
                        string             json     = Encoding.UTF8.GetString(bytes);
                        MethodCallbackInfo callback = ServerSerializationHelper.Deserialize <MethodCallbackInfo>(json, serverBase);
                        if (callback == null)
                        {
                            serverBase.AutoLogger.LogText($"{client.IPAddress} {client.ClientId} callback is null:" + json);
                        }
                        if (callback.PartNumber != 0)
                        {
                            SegmentManager segmentManager = new SegmentManager();
                            ISegment       result         = segmentManager.GenerateAndMixSegments(callback);
                            if (result != null)
                            {
                                callback = (MethodCallbackInfo)result;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        if (serverBase.ClientServiceCallMethodsResult.TryGetValue(callback.Guid, out KeyValue <Type, object> resultTask))
                        {
                            if (callback.IsException)
                            {
                                resultTask.Value.GetType().FindMethod("SetException").Invoke(resultTask.Value, new object[] { new Exception(callback.Data) });
                            }
                            else
                            {
                                resultTask.Value.GetType().FindMethod("SetResult").Invoke(resultTask.Value, new object[] { ServerSerializationHelper.Deserialize(callback.Data, resultTask.Key, serverBase) });
                            }
                        }
                    }
                    else if (dataType == DataType.GetServiceDetails)
                    {
                        byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock);

                        //if (ClientsSettings.ContainsKey(client))
                        //    bytes = DecryptBytes(bytes, client);
                        string json    = Encoding.UTF8.GetString(bytes);
                        string hostUrl = ServerSerializationHelper.Deserialize <string>(json, serverBase);
                        ServerServicesManager serverServicesManager = new ServerServicesManager();
                        ProviderDetailsInfo   detail = serverServicesManager.SendServiceDetail(hostUrl, serverBase);
                        json = ServerSerializationHelper.SerializeObject(detail, serverBase);
                        List <byte> resultBytes = new List <byte>
                        {
                            (byte)DataType.GetServiceDetails,
                            (byte)CompressMode.None
                        };
                        byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
                        byte[] dataLen   = BitConverter.GetBytes(jsonBytes.Length);
                        resultBytes.AddRange(dataLen);
                        resultBytes.AddRange(jsonBytes);
                        await client.StreamHelper.WriteToStreamAsync(client.ClientStream, resultBytes.ToArray());
                    }
                    else if (dataType == DataType.GetMethodParameterDetails)
                    {
                        byte[] bytes = await client.StreamHelper.ReadBlockToEndAsync(stream, compressMode, serverBase.ProviderSetting.MaximumReceiveDataBlock);

                        //if (ClientsSettings.ContainsKey(client))
                        //    bytes = DecryptBytes(bytes, client);
                        string json = Encoding.UTF8.GetString(bytes);
                        MethodParameterDetails detail = ServerSerializationHelper.Deserialize <MethodParameterDetails>(json, serverBase);

                        if (!serverBase.RegisteredServiceTypes.TryGetValue(detail.ServiceName, out Type serviceType))
                        {
                            throw new Exception($"{client.IPAddress} {client.ClientId} Service {detail.ServiceName} not found");
                        }
                        if (serviceType == null)
                        {
                            throw new Exception($"{client.IPAddress} {client.ClientId} serviceType {detail.ServiceName} not found");
                        }

                        ServerServicesManager serverServicesManager = new ServerServicesManager();

                        json = serverServicesManager.SendMethodParameterDetail(serviceType, detail, serverBase);
                        List <byte> resultBytes = new List <byte>
                        {
                            (byte)DataType.GetMethodParameterDetails,
                            (byte)CompressMode.None
                        };

                        byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
                        byte[] dataLen   = BitConverter.GetBytes(jsonBytes.Length);
                        resultBytes.AddRange(dataLen);
                        resultBytes.AddRange(jsonBytes);
                        await client.StreamHelper.WriteToStreamAsync(client.ClientStream, resultBytes.ToArray());
                    }
                    else if (dataType == DataType.GetClientId)
                    {
                        byte[]      bytes  = Encoding.UTF8.GetBytes(client.ClientId);
                        List <byte> result = new List <byte>();
                        result.Add((byte)DataType.GetClientId);
                        result.Add((byte)CompressMode.None);

                        result.AddRange(BitConverter.GetBytes(bytes.Length));
                        result.AddRange(bytes);
                        //if (ClientsSettings.ContainsKey(client))
                        //    bytes = EncryptBytes(bytes, client);
                        if (result.Count > serverBase.ProviderSetting.MaximumSendDataBlock)
                        {
                            throw new Exception($"{client.IPAddress} {client.ClientId} GetClientId data length exceeds MaximumSendDataBlock");
                        }

                        await client.StreamHelper.WriteToStreamAsync(client.ClientStream, result.ToArray());
                    }
                    else
                    {
                        //throw new Exception($"Correct DataType Data {dataType}");
                        serverBase.AutoLogger.LogText($"Correct DataType Data {oneByteOfDataType} {client.ClientId} {client.IPAddress}");
                        break;
                    }
                }
                serverBase.DisposeClient(client, null, "StartToReadingClientData while break");
            }
            catch (Exception ex)
            {
                serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase SignalGoDuplexServiceProvider StartToReadingClientData");
                serverBase.DisposeClient(client, null, "SignalGoDuplexServiceProvider StartToReadingClientData exception");
            }
        }
Esempio n. 7
0
        public static async Task StartToReadingClientData(TcpClient tcpClient, ServerBase serverBase, PipeNetworkStream reader, StringBuilder builder)
        {
            //Console.WriteLine($"Http Client Connected: {((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString().Replace("::ffff:", "")}");
            ClientInfo client = null;

            try
            {
                while (true)
                {
                    string line = await reader.ReadLineAsync();

                    builder.Append(line);
                    if (line == TextHelper.NewLine)
                    {
                        break;
                    }
                }
                string requestHeaders = builder.ToString();

                if (requestHeaders.Contains("Sec-WebSocket-Key"))
                {
                    tcpClient.ReceiveTimeout = -1;
                    tcpClient.SendTimeout    = -1;
                    client = serverBase.ServerDataProvider.CreateClientInfo(false, tcpClient, reader);
                    client.ProtocolType = ClientProtocolType.WebSocket;
                    client.IsWebSocket  = true;
                    string key          = requestHeaders.Replace("ey:", "`").Split('`')[1].Replace("\r", "").Split('\n')[0].Trim();
                    string acceptKey    = AcceptKey(ref key);
                    string newLine      = TextHelper.NewLine;

                    //var response = "HTTP/1.1 101 Switching Protocols" + newLine
                    string response = "HTTP/1.0 101 Switching Protocols" + newLine
                                      + "Upgrade: websocket" + newLine
                                      + "Connection: Upgrade" + newLine
                                      + "Sec-WebSocket-Accept: " + acceptKey + newLine + newLine;
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(response);
                    await client.ClientStream.WriteAsync(bytes, 0, bytes.Length);

                    client.StreamHelper = SignalGoStreamBase.CurrentBase;
                    client.ClientStream = new PipeNetworkStream(new WebSocketStream(client.TcpClient.GetStream()));
                    if (requestHeaders.Contains("SignalgoDuplexWebSocket"))
                    {
                        await SignalGoDuplexServiceProvider.StartToReadingClientData(client, serverBase);
                    }
                    else
                    {
                        //client.StreamHelper = SignalGoStreamWebSocketLlight.CurrentWebSocket;
                        //client.ClientStream = new PipeNetworkStream(new WebSocketStream(client.TcpClient.GetStream()));
                        //await WebSocketProvider.StartToReadingClientData(client, serverBase);

                        await HttpProvider.AddWebSocketHttpClient(client, serverBase);
                    }
                }
                else if (requestHeaders.Contains("SignalGoHttpDuplex"))
                {
                    client = serverBase.ServerDataProvider.CreateClientInfo(false, tcpClient, reader);
                    client.ProtocolType = ClientProtocolType.HttpDuplex;
                    client.StreamHelper = SignalGoStreamBase.CurrentBase;
                    await SignalGoDuplexServiceProvider.StartToReadingClientData(client, serverBase);
                }
                else
                {
                    try
                    {
                        //serverBase.TaskOfClientInfoes
                        client = (HttpClientInfo)serverBase.ServerDataProvider.CreateClientInfo(true, tcpClient, reader);
                        client.ProtocolType = ClientProtocolType.Http;
                        client.StreamHelper = SignalGoStreamBase.CurrentBase;

                        string[] lines = null;
                        if (requestHeaders.Contains(TextHelper.NewLine + TextHelper.NewLine))
                        {
                            lines = requestHeaders.Substring(0, requestHeaders.IndexOf(TextHelper.NewLine + TextHelper.NewLine)).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        else
                        {
                            lines = requestHeaders.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        if (lines.Length > 0)
                        {
                            string methodName = GetHttpMethodName(lines[0]);
                            string address    = GetHttpAddress(lines[0]);
                            if (requestHeaders != null)
                            {
                                ((HttpClientInfo)client).RequestHeaders = SignalGo.Shared.Http.WebHeaderCollection.GetHttpHeaders(lines.Skip(1).ToArray());
                            }

                            await HandleHttpRequest(methodName, address, serverBase, (HttpClientInfo)client);
                        }
                        else
                        {
                            serverBase.DisposeClient(client, tcpClient, "HttpProvider StartToReadingClientData no line detected");
                        }
                    }
                    catch
                    {
                        serverBase.DisposeClient(client, tcpClient, "HttpProvider StartToReadingClientData exception");
                    }
                }
            }
            catch (Exception ex)
            {
                //if (client != null)
                //serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase HttpProvider StartToReadingClientData");
                serverBase.DisposeClient(client, tcpClient, "HttpProvider StartToReadingClientData exception 2");
            }
        }