Пример #1
0
        private async Task TryConnectAsync(CancellationTokenSource cancellationTokenSource = null)
        {
            var invocatorContext = CreateInvocatorContext();
            var uri = new Uri($"ws://{invocatorContext.HostAddress}");

            _webSocket = new ClientWebSocket();
            _webSocket.Options.SetRequestHeader(SocketsConstants.ConnectorName, invocatorContext.ConnectorName);
            try
            {
                CancellationToken token = cancellationTokenSource != null ? cancellationTokenSource.Token : CancellationToken.None;
                await _webSocket.ConnectAsync(uri, token);
            }
            catch (Exception ex)
            {
                ProxyLogHelper.Log(_loggerFactory, invocatorContext, "Error", ex);
                return;
            }

            var receiverContext = new WebSocketReceiverContext
            {
                Compressor       = _compressor,
                InvocatorContext = invocatorContext,
                LoggerFactory    = _loggerFactory,
                WebSocket        = _webSocket
            };
            var receiver = new WebSocketReceiver(_serviceProvider, receiverContext, Close, (connectionId) => {
                _connectionId = connectionId;
            });
            await receiver.ReceiveAsync();
        }
Пример #2
0
        /// <summary>
        /// 处理请求
        /// </summary>
        /// <returns></returns>
        public async Task Invoke(HttpContext context, IMessageService messageService)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                    await SendMessageAsync("新人加入");

                    var id = _webSocketManager.Add(webSocket);


                    var receiver = new WebSocketReceiver(webSocket, _webSocketManager, messageService);
                    receiver.MessageHandler += async(obj, e) =>
                    {
                        await SendMessageAsync(msg : $"send people:{webSocket.GetHashCode()}.receive content:{e.Message.Content}.send content:{Guid.NewGuid()}");
                    };
                    await receiver.StartListening();


                    await _webSocketManager.Remove(id);
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
                return;
            }

            await _next.Invoke(context);
        }
Пример #3
0
        public void execute(WebSocketReceiver receiver, string[] packet)
        {
            try
            {
                switch (packet[1])
                {
                case "auth":
                    var userId   = 0;
                    var playerId = 0;
                    if (int.TryParse(packet[2], out userId) && int.TryParse(packet[3], out playerId))
                    {
                        var admin = new Admin(userId, playerId, packet[4], DateTime.Now);
                        admin.BeginAuth();
                        //todo...
                    }
                    break;

                case "box":
                    break;

                case "object":
                    break;

                case "resource":
                    break;
                }
            }
            catch
            {
            }
        }
 public void execute(WebSocketReceiver receiver, string[] packet)
 {
     try
     {
         var userId = packet[1];
     }
     catch { }
 }
Пример #5
0
        public static void Handle(WebSocketReceiver receiver, string packet)
        {
            IHandler handler;
            var      finalPacket = packet.Contains("|") ? packet.Split('|') : new[] { packet };

            HandledPackets.TryGetValue(finalPacket[0], out handler);
            handler?.execute(receiver, finalPacket);
            receiver.Send("success");
        }
Пример #6
0
        private void Start()
        {
            _started = true;
            StartCommand.RaiseCanExecuteChanged();

            _receiver = new WebSocketReceiver(_uri, _repository.GetRepositoryHash());
            var receiveListener = new ReceiveListener(_repository, _receiver);

            receiveListener.Start();
        }
Пример #7
0
        static void Main(string[] args)
        {
            var repository      = new PlanetRepository();
            var childRepository = new PlanetRepository();

            var collection = new RepositoryObservableCollection <Planet>(childRepository);

            /*
             * var sendListener = new TestSendListener(repository);
             * var receiver = new TestReceiver();
             * var receiveListener = new ReceiveListener(childRepository, receiver);
             * receiveListener.Start();
             * sendListener.Listen(receiver);
             */

            childRepository.SubscribeToRowAdded(r => Console.WriteLine("Row Added with Id {0}", r.RowId));
            childRepository.SubscribeToRowRemoved(r => Console.WriteLine("Row Removed with Id {0}", r.RowId));
            childRepository.SubscribeToCellUpdated(u => Console.WriteLine("Cell" + "Updated {0}:{1}:{2}", u.RowId, u.ColumnId, u));

            var mercury = repository.AddRow("Mercury", 57900000, TimeSpan.FromDays(59), 0.38);
            var venus   = repository.AddRow("Venus", 108160000, TimeSpan.FromDays(243), 0.9);
            var earth   = repository.AddRow("Earth", 149600000, TimeSpan.FromHours(23) + TimeSpan.FromMinutes(56), 1);
            var mars    = repository.AddRow("Mars", 141700000, TimeSpan.FromHours(24) + TimeSpan.FromMinutes(37), 0.38);
            var jupiter = repository.AddRow("Jupiter", 778369000, TimeSpan.FromHours(9) + TimeSpan.FromMinutes(55), 2.64);
            var saturn  = repository.AddRow("Saturn", 1427034000, TimeSpan.FromHours(10) + TimeSpan.FromMinutes(39), 1.16);
            var uranus  = repository.AddRow("Uranus", 2870658186, TimeSpan.FromHours(17) + TimeSpan.FromMinutes(14), 1.11);
            var neptune = repository.AddRow("Neptune", 4496976000, TimeSpan.FromHours(16) + TimeSpan.FromMinutes(7), 1.21);

            var sendListener    = new WebSocketSendListener(repository);
            var receiver        = new WebSocketReceiver("ws://localhost:8080/planet", childRepository.GetRepositoryHash());
            var receiveListener = new ReceiveListener(childRepository, receiver);

            receiveListener.Start();
            sendListener.Start("ws://0.0.0.0:8080/planet");

            Console.ReadKey();

            Console.WriteLine(childRepository.ToString());

            venus.Set(repository.Gravity, 0.88);
            saturn.Set(repository.DistanceFromSun, 1427034111);

            repository.RemoveRow(uranus);
            var uranus2 = repository.AddRow("Uranus II", 2870658186, TimeSpan.FromHours(17) + TimeSpan.FromMinutes(14), 1.11);

            Console.WriteLine();
            Console.WriteLine(childRepository.ToString());


            Console.ReadKey();
        }
Пример #8
0
        public void execute(WebSocketReceiver receiver, string[] packet)
        {
            try
            {
                var userId        = int.Parse(packet[1]);
                var playerSession = World.StorageManager.GetGameSession(userId);
                if (playerSession == null)
                {
                    return;
                }

                var player = playerSession.Player;
                switch (packet[2])
                {
                case "update_ammo":
                    player.Information.Ammunitions = World.DatabaseManager.LoadAmmunition(player);
                    Packet.Builder.SendSlotbars(playerSession);
                    break;

                case "new_drone":
                    player.Equipment.Reload();
                    Packet.Builder.DronesCommand(playerSession, player);
                    Packet.Builder.DroneFormationAvailableFormationsCommand(playerSession);
                    break;

                case "new_pet":
                    player.Pet = World.DatabaseManager.LoadPet(player);
                    Packet.Builder.PetInitializationCommand(playerSession, player.Pet);
                    break;

                case "refuel":
                    //todo
                    //player.Pet.Fuel = World.DatabaseManager.GetPetFuel();
                    break;

                case "update_boosters":
                    player.Boosters = World.DatabaseManager.LoadBoosters(player);
                    Packet.Builder.AttributeBoosterUpdateCommand(playerSession);
                    break;

                case "update_keys":
                    player.Information.UpdateExtraData();
                    player.Information.DisplayBootyKeys();
                    break;
                }
            }
            catch
            {
            }
        }
Пример #9
0
        public async Task ConnectAsync(WebSocket webSocket, string connectionId, string connectorName = "")
        {
            var receiverContext = new WebSocketReceiverContext
            {
                Compressor    = _compressor,
                ConnectionId  = connectionId,
                LoggerFactory = _loggerFactory,
                WebSocket     = webSocket
            };

            WebSocketTransport transport = null;

            if (Connections.TryGetValue(connectionId, out transport))
            {
                transport.ReConnect(webSocket);
                List <MessageHolder> messages = _lifetimeManager.TryDequeue(connectionId);
                foreach (var message in messages)
                {
                    await SendAsync(transport, new WebSocketMessageDescriptor
                    {
                        MessageType  = WebSocketMessageType.Text,
                        Segments     = message.Segments,
                        EndOfMessage = true,
                        IsQueue      = true,
                    });
                }
            }
            else
            {
                transport = new WebSocketTransport(webSocket, connectionId, connectorName);
                var context = new WebSocketMessageContext();
                context.Command = WebSocketCommands.Handshake;
                context.Value   = connectionId;
                context.Header  = await _initState.GetStateAsync();

                Connections.TryAdd(connectionId, transport);

                await SendAsync(connectionId, context);
            }

            var receiver = new WebSocketReceiver(_serviceProvider, receiverContext, CloseConnection);
            await receiver.ReceiveAsync();
        }
Пример #10
0
 public void execute(WebSocketReceiver receiver, string[] packet)
 {
     switch (packet[1])
     {
     case "req":
         switch (packet[2])
         {
         case "payload":
             var servers = Global.QueryManager.GetServers();
             var user    = Global.QueryManager.GetUser(Convert.ToInt32(packet[3]));
             var payload = new Payload {
                 Servers = servers, User = user
             };
             receiver.Send("payload|" + JsonConvert.SerializeObject(payload));
             break;
         }
         break;
     }
 }
Пример #11
0
        public async Task ConnectAsync(WebSocket webSocket,
                                       string connectionId,
                                       string connectorName = "",
                                       CancellationToken cancellationToken = default(CancellationToken))
        {
            if (cancellationToken != CancellationToken.None)
            {
                cancellationToken.Register(() =>
                {
                    CancellationGraceful();
                });
            }

            var receiverContext = new WebSocketReceiverContext
            {
                Compressor       = _compressor,
                ConnectionId     = connectionId,
                LoggerFactory    = _loggerFactory,
                WebSocket        = webSocket,
                InvocatorContext = InvocatorContext
            };

            if (Connections.TryGetValue(connectionId, out WebSocketTransport transport))
            {
                transport.ReConnect(webSocket);
            }
            else
            {
                transport = new WebSocketTransport(webSocket, connectionId, connectorName);
                var context = new WebSocketMessageContext();
                context.Command = WebSocketCommands.Handshake;
                context.Value   = connectionId;
                context.Header  = await _initState.GetStateAsync();

                Connections.TryAdd(connectionId, transport);

                await SendAsync(connectionId, context);
            }

            var receiver = new WebSocketReceiver(_serviceProvider, receiverContext, CloseConnection, _loggerFactory);
            await receiver.ReceiveAsync(cancellationToken);
        }
Пример #12
0
        public void execute(WebSocketReceiver receiver, string[] packet)
        {
            try
            {
                var userId = int.Parse(packet[1]);
                switch (packet[2])
                {
                case "new_create":
                    break;

                case "update_members":
                    break;

                case "left_clan":
                    break;
                }
            }
            catch
            {
            }
        }
Пример #13
0
        public void execute(WebSocketReceiver receiver, string[] packet)
        {
            try
            {
                int userId;
                if (!int.TryParse(packet[2], out userId))
                {
                    return;
                }

                var gameSession = World.StorageManager.GetGameSession(userId);
                var player      = gameSession?.Player;
                if (player == null)
                {
                    return;
                }
                switch (packet[1])
                {
                case "eq":
                    if (player.State.InEquipmentArea)
                    {
                        player.Equipment.Reload();
                        player.Refresh();
                        player.State.WaitingForEquipmentRefresh = false;
                    }
                    else
                    {
                        player.State.WaitingForEquipmentRefresh = true;
                    }
                    break;
                }
            }
            catch
            {
            }
        }