예제 #1
0
        static async void ConnectNatServer()
        {
            try
            {
                if (!IsReConnect)
                {
                    return;
                }
                isLock = true;
                LogHelper.Info($"正在连接服务器...");
                //解析主机名
                var serverIp = ServerUrl;
                var ipArr    = ServerUrl.Split('.');
                //先判断是不是IP,不是IP就尝试解析域名
                if (ipArr.Where(c => int.TryParse(c, out int i) && i > 0 && i <= 255).Count() != 4)
                {
                    IPHostEntry ipInfo = Dns.GetHostEntry(ServerUrl);
                    serverIp = ipInfo.AddressList.Any() ? ipInfo.AddressList[0].ToString() : throw new Exception($"域名【{ServerUrl}】无法解析");
                }
                NatClient = new NatClient(new ClientOption()
                {
                    Ip           = serverIp,
                    Port         = NatPort,
                    NoDelay      = true,
                    ProtocolType = ProtocolType.Tcp,
                    Security     = SslProtocols.Tls12,
                    SslClientAuthenticationOptions = new SslClientAuthenticationOptions
                    {
                        EnabledSslProtocols = SslProtocols.Tls12,
                        TargetHost          = serverIp,
                        ClientCertificates  = new X509CertificateCollection()
                        {
                            new X509Certificate(CertFile, CertPassword)
                        }
                    }
                });
                NatClient.OnConnected += OnClientConnected;
                NatClient.OnReceived  += OnPackageReceived;
                NatClient.OnClosed    += OnClientClosed;

                await NatClient.ConnectAsync();
            }
            catch (Exception ex)
            {
                LogHelper.Error($"连接服务器失败:{ex}");
            }

            isLock = false;
        }
예제 #2
0
        /// <summary>
        /// Callback for OpenAsync calls
        /// </summary>
        /// <param name="sender">should be this object</param>
        /// <param name="e">Event Args holding the login information from Salesforce</param>
        private void ls_restloginCompleted(object sender, loginCompletedEventArgs e)
        {
            LoginTime                    = DateTime.Now;
            Url                          = e.Result.serverUrl;
            SessionHeaderValue           = new SessionHeader();
            SessionHeaderValue.sessionId = e.Result.sessionId;

            SessionId = e.Result.sessionId;
            ServerUrl = e.Result.serverUrl;

            string[] pieces = ServerUrl.Split('/');

            Version = pieces[pieces.Length - 2];

            ApiEndPoint = new Uri(e.Result.serverUrl);

            baseUrl = "https://" + ApiEndPoint.Host;

            state = ConnectionState.Open;
        }
        public void SendMessage()
        {
            string clearXmlRequest      = XmlRequest;
            int    serverConnectTimeout = 5000; // 5 Seconds

            //DevelopmentLicence myForm = new DevelopmentLicence();
            // myForm.ShowDialog();
            // used new methods
            // string base64String = Convert.ToBase64String(Encoding.Default.GetBytes(XmlRequest));
            //XmlRequest = base64String;

            _myStatusForm = new StatusForm();
            _myStatusForm.Show();
            _myStatusForm.BringToFront();
            _myStatusForm.Refresh();

            try
            {
                string[] serveripandport;
                serveripandport = ServerUrl.Split(':');
                string ip   = serveripandport[0];
                int    port = System.Convert.ToInt32(serveripandport[1]);

                //TcpClient client = new TcpClient(ip, port);
                connectDone.Reset();
                TcpClient client = new TcpClient();
                try
                {
                    OnStatusMessage(STR_Connecting);
                    client.BeginConnect(ip, port, new AsyncCallback(ConnectCallback), client); // here the clients starts to connect asynchronously (because it is asynchronous it doesn't have a timeout only events are triggered)
                    // immediately after calling beginconnect the control is returned to the method, now we need to wait for the event or connection timeout
                    connectDone.WaitOne(serverConnectTimeout, false);                          // now application waits here for either an connection event (fi. connection accepted) or the timeout specified by connectionTimeout (in milliseconds)

                    if (!client.Connected)
                    {
                        throw new SocketException(10061);
                    }                                                            /*10061 = Could not connect to server */

                    client.SendTimeout    = timeout;
                    client.ReceiveTimeout = timeout;
                    // client.NoDelay = true;
                    client.ReceiveBufferSize = 32768;
                    // First 20 bytes = length in Ascii.
                    //string messageSize = "00000000000000000000" + XmlRequest.Length;
                    //messageSize = messageSize.Substring(messageSize.Length - 20);
                    //XmlRequest = messageSize + XmlRequest;
                    XmlRequest = encodeXmlMessage(XmlRequest, true);
                    OnStatusMessage(STR_Sending);
                    Byte[] request = Encoding.Default.GetBytes(XmlRequest);
                    client.GetStream().Write(request, 0, request.Length);
                    client.GetStream().Flush();

                    byte[] xmlLength;
                    string messageLength;
                    int    lenbytesRead;
                    bool   messageLoop = false;
                    bool   statusLoop  = true;
                    do
                    {
                        // Big Status Loop.
                        do
                        {
                            // Inner Ack Loop, maybe we can get rid off.
                            xmlLength     = new byte[20];
                            messageLength = "";
                            lenbytesRead  = client.GetStream().Read(xmlLength, 0, 20);//s.Receive(incomingBuffer);
                            messageLength = Encoding.Default.GetString(xmlLength);
                            // Log("Message size is " + messageLength);
                            switch (messageLength)
                            {
                            case STR_ACK00000000000000000:
                                OnStatusMessage(STR_AckReceived);
                                messageLoop = true;
                                break;

                            default:

                                OnStatusMessage(STR_Reading);
                                messageLoop = false; break;
                            }
                        } while (messageLoop && client.Connected);
                        int xmlMessageSize = Convert.ToInt32(messageLength);

                        List <byte> dataBuffer     = new List <byte>();
                        int         bytesReadSoFar = 0;
                        do
                        {
                            Byte[] response  = new Byte[client.ReceiveBufferSize];
                            int    bytesRead = client.GetStream().Read(response, 0, client.ReceiveBufferSize);
                            bytesReadSoFar += bytesRead;
                            byte[] resultArray = new byte[bytesRead];
                            Array.Copy(response, resultArray, bytesRead);
                            dataBuffer.AddRange(resultArray);
                        } while (bytesReadSoFar < xmlMessageSize);

                        XmlResponse = Encoding.Default.GetString(dataBuffer.ToArray(), 0, dataBuffer.Count).Trim();

                        //Log("Received response: " + XmlResponse);
                        if (XmlResponse.IndexOf('<') < 0)
                        {
                            //  Log("Message was encrypted");
                            XmlResponse = XmlResponse.Replace("\0", "");
                            XmlResponse = decodeXmlMessage(XmlResponse, true);
                        }
                        if (XmlResponse.IndexOf("<StatusResponse") > 0)
                        {
                            //Do something with the status message....
                            try
                            {
                                XmlSerializer serializer = new XmlSerializer(typeof(HicapsConnectControl.StatusResponse));
                                MemoryStream  myResultMS = new MemoryStream(Encoding.Default.GetBytes(XmlResponse));
                                HicapsConnectControl.StatusResponse myResult = (HicapsConnectControl.StatusResponse)serializer.Deserialize(myResultMS);
                                OnStatusMessage(myResult.ResponseText);
                                statusLoop = true;
                            }
                            catch (Exception ex)
                            {
                                statusLoop = false;
                            }
                        }
                        else
                        {
                            statusLoop = false;
                        }
                    } while (client.Connected && statusLoop);
                    client.Close();
                }
                catch (SocketException)
                {
                    string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest);
                    XmlResponse = returnNetworkErrorXml("ED", String.Format(STR_DestinationErrorCouldNotConnectToServer, ServerUrl), className);
                }
                catch (TimeoutException)
                {
                    string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest);
                    XmlResponse = returnNetworkErrorXml("EN", String.Format(STR_NetworkRequestTimedOut, ServerUrl), className);
                }
                catch (Exception)
                {
                    string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest);
                    XmlResponse = returnNetworkErrorXml("EN", STR_NetworkError, className);
                }

                client.Close();

                //Console.ReadLine();

                //client.Close();
            }
            catch (Exception ex)
            {
                //lock (ignoreServerList)
                //{
                //    if (!ignoreServerList.Contains(server))
                //    {
                //        ignoreServerList.Add(server);
                //    }
                //}
            }
            if (XmlResponse.Length == 0 || XmlResponse == "Que ? Go away")
            {
                string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest);
                XmlResponse = returnNetworkErrorXml("EN", "Network Error", className);
            }
            OnStatusMessage("Waiting");
            OnCompletedMessage();
            return;
        }