Exemplo n.º 1
0
 public ITypeProtocolClient AsClient(IPEndPoint ipEndPoint)
 {
     type = "CLIENT";
     using (var session = new Session())
     {
         this.ipEndPoint = ipEndPoint;
         session.Log("CLIENT: Connecting Tcp Socket: {0}", this.ipEndPoint);
         TryingExtensions.UntilNoException(
             () => { this.socket.Connect(this.ipEndPoint); },
             (e) =>
             {
                 session.Log("Tcp Socket Connection Error: {0}", e);
                 session.Flush();
                 Thread.Sleep(50);
             },
             cancellationToken);
         return this;
     }
 }
Exemplo n.º 2
0
        public string Send(string payload)
        {
            using (var session = new Session())
            {
                Debug.Assert(this.ipEndPoint != null, "Please call AsClient with a valid ipEndPoint");

                var payloadBytes = Encoding.UTF8.GetBytes(payload).Concat(ServerConstants.INSTANCE_PUB_SUB_TERMINATOR).ToArray();

                TryingExtensions.WithContinue(() =>
                {
                    session.Log("CLIENT: Sending {0}: {1}", this.ipEndPoint, payload);
                    this.socket.Send(payloadBytes);
                }, (e) =>
                {
                    session.Log("CLIENT: Error Sending {0}: {1}. Trying again.", this.ipEndPoint, e);
                    session.Flush();
                    AsClient(this.ipEndPoint);
                    TryingExtensions.WithContinue(() =>
                    {
                        this.socket.Send(payloadBytes);
                    });
                });

                var numberOfBytes = 0;
                var receiveString = string.Empty;
                var receiveBytes = new byte[1024];

                TryingExtensions.WithContinue(() =>
                {
                    session.Log("CLIENT: Receving from {0}", this.ipEndPoint);
                    numberOfBytes = this.socket.Receive(receiveBytes);
                }, (e) =>
                {
                    session.Log("CLIENT: Receiving Error {0}: {1}. Trying again.", this.ipEndPoint, e);
                    numberOfBytes = 0;
                });

                if (numberOfBytes == 0)
                {
                    session.Log("CLIENT: Error State, returning string.Empty");
                    return string.Empty;
                }

                receiveString += Encoding.UTF8.GetString(receiveBytes, 0, numberOfBytes);
                session.Log("CLIENT: Received {0}", receiveString);
                return receiveString;
            }
        }