/// Called when an incoming message is received
        public override void MessageReceived(NetClientBase client_in, BaseMessage msg_in)
        {
            Console.WriteLine($"App: Received: from {client_in.GetNicePeerAddr()} '{msg_in.ToString()}'");
            switch (msg_in.GetType())
            {
            case MessageType.Handshake:
            {
                HandshakeMessage hsMsg = msg_in as HandshakeMessage;
                //cout << "Handshake message received, '" << hsMsg.getMyAddr() << "'" << endl;
                if (hsMsg.GetMyVersion() != "V01")
                {
                    Console.Error.WriteLine($"Wrong version '{hsMsg.GetMyVersion()}'");
                    client_in.Close();
                    return;
                }
                HandshakeResponseMessage resp = new HandshakeResponseMessage("V01", myName, client_in.GetPeerAddr());
                client_in.SendMessage(resp);
            }
            break;

            case MessageType.Ping:
            {
                PingMessage pingMsg = msg_in as PingMessage;
                //cout << "Ping message received, '" << pingMsg.GetText() << "'" << endl;
                PingResponseMessage resp = new PingResponseMessage("Resp_from_" + myName + "_to_" + pingMsg.GetText());
                client_in.SendMessage(resp);
            }
            break;

            default:
                System.Diagnostics.Debug.Assert(false);
                break;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Handles an incoming handshake request. We should only receive one of these!
        /// </summary>
        protected async Task handleHandshakeRequestMessage(HandshakeRequestMessage message)
        {
            CurrentViewPort        = message.InitialViewport;
            AbsoluteCursorPosition = message.InitialAbsCursorPosition;

            // Tell everyone else about the new client
            ClientStatesMessage newClientNotification = new ClientStatesMessage();

            newClientNotification.ClientStates.Add(GenerateStateSnapshot());
            await manager.Broadcast(this, newClientNotification);

            // Send the new client a response to their handshake request
            HandshakeResponseMessage handshakeResponse = new HandshakeResponseMessage();

            handshakeResponse.Id     = Id;
            handshakeResponse.Colour = Colour;
            handshakeResponse.Name   = Name;
            foreach (Plane plane in manager.NibriServer.PlaneManager.Planes)
            {
                handshakeResponse.Planes.Add(plane.Name);
            }

            await Send(handshakeResponse);

            // Tell the new client about everyone else who's connected
            // FUTURE: If we need to handle a large number of connections, we should generate this message based on the chunks surrounding the client
            await Send(GenerateClientStateUpdate());
        }
Exemplo n.º 3
0
    /// <summary>
    /// Writes the serialized representation of a <see cref="HandshakeResponseMessage"/> to the specified writer.
    /// </summary>
    /// <param name="responseMessage">The message to write.</param>
    /// <param name="output">The output writer.</param>
    public static void WriteResponseMessage(HandshakeResponseMessage responseMessage, IBufferWriter <byte> output)
    {
        var reusableWriter = ReusableUtf8JsonWriter.Get(output);

        try
        {
            var writer = reusableWriter.GetJsonWriter();

            writer.WriteStartObject();
            if (!string.IsNullOrEmpty(responseMessage.Error))
            {
                writer.WriteString(ErrorPropertyNameBytes, responseMessage.Error);
            }

            writer.WriteEndObject();
            writer.Flush();
            Debug.Assert(writer.CurrentDepth == 0);
        }
        finally
        {
            ReusableUtf8JsonWriter.Return(reusableWriter);
        }

        TextMessageFormatter.WriteRecordSeparator(output);
    }
Exemplo n.º 4
0
        private static async Task ProvideServerHandshake(PipeReader reader, PipeWriter writer, CancellationToken cancellationToken)
        {
            bool isHandshakeCompleted = false;

            while (!isHandshakeCompleted)
            {
                var result = await reader.ReadAsync(cancellationToken).ConfigureAwait(false);

                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                var buffer = result.Buffer;
                if (HandshakeProtocol.TryParseRequestMessage(ref buffer, out var requestMessage))
                {
                    var responseMessage = HandshakeResponseMessage.Empty;
                    if (requestMessage.Protocol != nameof(MessageStoreHubProtocol))
                    {
                        responseMessage = new HandshakeResponseMessage($"Protocol '{requestMessage.Protocol}' is not supported.");
                    }

                    reader.AdvanceTo(buffer.Start, buffer.Start);

                    HandshakeProtocol.WriteResponseMessage(responseMessage, writer);
                    await writer.FlushAsync(cancellationToken).ConfigureAwait(false);

                    isHandshakeCompleted = true;
                }
        public static bool TryParseHandshakeResponseMessage(string message, out HandshakeResponseMessage responseMessage)
        {
            if ("{}".Equals(message))
            {
                responseMessage = HandshakeResponseMessage.Empty;
                return(true);
            }
            try
            {
                responseMessage = JsonConvert.DeserializeObject <HandshakeResponseMessage>(message, _serializerSettings);
            }
            catch (JsonSerializationException)
            {
                Log.Debug("客户端与服务器的协议不一致");
                responseMessage = null;
                return(false);
            }

            if (responseMessage.Type != null &&
                responseMessage.Type >= HubProtocolConstants.InvocationMessageType &&
                responseMessage.Type <= HubProtocolConstants.CloseMessageType)
            {
                // a handshake response does not have a type
                Log.Debug($"a handshake response does not have a type. type={responseMessage.Type}");
                responseMessage = null;
                return(false);
            }
            return(true);
        }
Exemplo n.º 6
0
        private void ProcessHandhakeResponse(HandshakeResponseMessage response)
        {
            switch (response.Location)
            {
            case CellNeighbourhood.Row:
                if (Sender != Self)
                {
                    rowCells.Add(Sender);
                }
                break;

            case CellNeighbourhood.Column:
                if (Sender != Self)
                {
                    columnCells.Add(Sender);
                }
                break;

            case CellNeighbourhood.Square:
                if (Sender != Self)
                {
                    squareCells.Add(Sender);
                }
                break;
            }

            if (rowCells.Count == 8 && columnCells.Count == 8 && squareCells.Count == 8)
            {
                Context.Parent.Tell(new HandshakeDoneMessage(cellNumber));
            }
        }
Exemplo n.º 7
0
        public async Task <Task> ConnectAsync(
            EndPoint endPoint,
            bool sendHandshakeRequestMessage      = true,
            bool expectedHandshakeResponseMessage = true)
        {
            if (sendHandshakeRequestMessage)
            {
                using (var memoryStream = new MemoryStream())
                {
                    HandshakeProtocol.WriteRequestMessage(new HandshakeRequestMessage(_protocol.Name), memoryStream);
                    await Connection.Application.Output.WriteAsync(memoryStream.ToArray());
                }
            }

            var connection = endPoint.OnConnectedAsync(Connection);

            if (expectedHandshakeResponseMessage)
            {
                // note that the handshake response might not immediately be readable
                // e.g. server is waiting for request, times out after configured duration,
                // and sends response with timeout error
                HandshakeResponseMessage = (HandshakeResponseMessage) await ReadAsync(true).OrTimeout();
            }

            return(connection);
        }
Exemplo n.º 8
0
    /// <summary>
    /// Creates a new <see cref="HandshakeResponseMessage"/> from the specified serialized representation.
    /// </summary>
    /// <param name="buffer">The serialized representation of the message.</param>
    /// <param name="responseMessage">When this method returns, contains the parsed message.</param>
    /// <returns>A value that is <c>true</c> if the <see cref="HandshakeResponseMessage"/> was successfully parsed; otherwise, <c>false</c>.</returns>
    public static bool TryParseResponseMessage(ref ReadOnlySequence <byte> buffer, [NotNullWhen(true)] out HandshakeResponseMessage?responseMessage)
    {
        if (!TextMessageParser.TryParseMessage(ref buffer, out var payload))
        {
            responseMessage = null;
            return(false);
        }

        var reader = new Utf8JsonReader(payload, isFinalBlock: true, state: default);

        reader.CheckRead();
        reader.EnsureObjectStart();

        string?error = null;

        while (reader.CheckRead())
        {
            if (reader.TokenType == JsonTokenType.PropertyName)
            {
                if (reader.ValueTextEquals(TypePropertyNameBytes.EncodedUtf8Bytes))
                {
                    // a handshake response does not have a type
                    // check the incoming message was not any other type of message
                    throw new InvalidDataException("Expected a handshake response from the server.");
                }
                else if (reader.ValueTextEquals(ErrorPropertyNameBytes.EncodedUtf8Bytes))
                {
                    error = reader.ReadAsString(ErrorPropertyName);
                }
                else
                {
                    reader.Skip();
                }
            }
            else if (reader.TokenType == JsonTokenType.EndObject)
            {
                break;
            }
            else
            {
                throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading handshake response JSON.");
            }
        }
        ;

        responseMessage = new HandshakeResponseMessage(error);
        return(true);
    }
Exemplo n.º 9
0
        public Task StartAsync()
        {
            _processIncoming = Task.Run(async() =>
            {
                while (true)
                {
                    var result = await MockServicePipe.Input.ReadAsync();
                    if (result.IsCanceled || result.IsCompleted)
                    {
                        break;
                    }

                    var buffer = result.Buffer;

                    try
                    {
                        if (!buffer.IsEmpty)
                        {
                            while (_servicePro.TryParseMessage(ref buffer, out var message))
                            {
                                if (message is HandshakeRequestMessage)
                                {
                                    var handshakeResponse = new HandshakeResponseMessage("");
                                    _servicePro.WriteMessage(handshakeResponse, MockServicePipe.Output);
                                    var flushResult = await MockServicePipe.Output.FlushAsync();
                                    if (flushResult.IsCanceled || flushResult.IsCompleted)
                                    {
                                        CompletedServiceConnectionHandshake.TrySetResult(false);
                                    }
                                    else
                                    {
                                        CompletedServiceConnectionHandshake.TrySetResult(true);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    finally
                    {
                        MockServicePipe.Input.AdvanceTo(buffer.Start, buffer.End);
                    }
                }
            });
            return(Task.CompletedTask);
        }
Exemplo n.º 10
0
 // internal to only allow FayeClient to instantiate this class
 internal FayeConnection(ITransportConnection connection,
                         HandshakeResponseMessage handshakeResponse,
                         int messageCounter,
                         Advice advice,
                         TimeSpan handshakeTimeout,
                         string connectionId) : base(messageCounter: messageCounter,
                                                     handshakeTimeout: handshakeTimeout)
 {
     _connection = connection;
     ClientId    = handshakeResponse.ClientId;
     _connection.MessageReceived += SocketMessageReceived;
     _subscribedChannels          = new Dictionary <string, List <Action <string> > >();
     _synchronousMessageEvents    = new Dictionary <int, TaskCompletionSource <MessageReceivedArgs> >();
     _advice = advice;
     _connection.ConnectionLost          += SocketConnectionLost;
     _connection.ConnectionReestablished += SocketConnectionReestablished;
     _logger = LoggerFetcher.GetLogger(connectionId,
                                       this);
 }
 private bool HandshakeResponseMessagesEqual(HandshakeResponseMessage x, HandshakeResponseMessage y)
 {
     return(StringEqual(x.ErrorMessage, y.ErrorMessage));
 }
Exemplo n.º 12
0
 private void ReceiveHandshakeResponseMessage(HandshakeResponseMessage message)
 {
     Context.Watch(Context.Sender);
 }
Exemplo n.º 13
0
 public static Task SendHandshakeResponseAsync(PipeWriter output, HandshakeResponseMessage response = null)
 {
     ServiceProtocol.WriteMessage(response ?? new HandshakeResponseMessage(), output);
     return(output.FlushAsync().AsTask());
 }