Exemple #1
0
        public async Task ShouldSendEventsWithArraybuffersInTheCorrectOrder()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag             = false;
            var buf = System.Text.Encoding.UTF8.GetBytes("abuff1");

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("abuff2-ack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });


            await Task.Delay(5000);

            socket.Emit("abuff1", buf);
            socket.Emit("abuff2", "please arrive second");
            ManualResetEvent.WaitOne();
            Assert.True(Flag);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            socket.Emit("entrar", "matheus");

            //armazena a imagem no bitmap
            Bitmap b = new Bitmap(TelaLargura, TelaAltura);

            //copia  a tela no bitmap
            g = Graphics.FromImage(b);
            g.CopyFromScreen(Point.Empty, Point.Empty, Screen.PrimaryScreen.Bounds.Size);
            //atribui a imagem ao picturebox exibindo-a
            //picTela.Image = b;
            this.Show();
            //habilita o botão para salvar a tela
            /**/
            byte[] bufferTempTemp = imageToByteArray(b);
            Image  img            = byteArrayToImage(bufferTempTemp);

            picTela.Image = img;
            //socket.Emit("imagem", bufferTempTemp);
            //socket.Emit("update", "teste");
            /**/


            string img64Bit = ConvertImageToBase64String(img);
            Image  newImg   = ConvertBase64StringToImage(img64Bit);

            socket.Emit("imagem", img64Bit);
        }
 public void EnviarAtividade(string atividade)
 {
     try
     {
         socket.Emit("atividade", atividade);
     }
     catch { }
 }
Exemple #4
0
        public void connected(Quobject.SocketIoClientDotNet.Client.Socket socket, string name)
        {
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                MessageBox.Show("connected", "Thông báo ");
            });
            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                MessageBox.Show(data.ToString());
            });
            socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
            {
                MessageBox.Show(data.ToString());
            });


            socket.On("ChatMessage", (data) =>
            {
                MessageBox.Show(data.ToString());
                if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() == "Welcome!")
                {
                    socket.Emit("MyNameIs", name);
                    socket.Emit("ConnectToOtherPlayer");
                }
                string mes = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                if (mes.Contains("You are the first player!") == true)
                {
                    activer = 2;
                }
            });

            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                MessageBox.Show(data.ToString());
            });


            socket.On("NextStepIs", (data) =>
            {
                MessageBox.Show(data.ToString());
                var o   = JObject.Parse(data.ToString());
                activer = (int)o["player"];
                row     = (int)o["row"];
                column  = (int)o["col"];
                MessageBox.Show(row + "  " + column + "   " + activer);
                if (activer == 1)
                {
                    board.play(column, row, activer);
                    activer = 2;
                }

                if (activer == 2)
                {
                    activer = 2;
                }
            });
        }
Exemple #5
0
        public static void KetNoi(Quobject.SocketIoClientDotNet.Client.Socket socket, string name)
        {
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                MessageBox.Show("Connected", "Thông báo", MessageBoxButton.OK);
            });
            //socket.On(Socket.EVENT_MESSAGE, (data) =>
            //{
            //    MessageBox.Show(data.ToString());
            //    _mes = data.ToString();
            //});

            socket.On("ChatMessage", (data) =>
            {
                //string s = "You are the first player!";
                //turn = data.ToString().Contains(s);
                string ten = "";
                var o      = JObject.Parse(data.ToString());
                if ((string)o["from"] != null)
                {
                    ten = (string)o["from"];
                }
                else
                {
                    ten = "Server";
                }
                var jobject       = data as JToken;
                AppSetting.a.Mes += ten + "\n" + jobject.Value <String>("message") + "  " + DateTime.Now.ToString() + "\n\n";

                if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() == "Welcome!")
                {
                    socket.Emit("MyNameIs", name);
                    socket.Emit("ConnectToOtherPlayer");
                    _name = name;
                }
            });
            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                MessageBox.Show(data.ToString());
            });
            socket.On("NextStepIs", (data) =>
            {
                var jobject          = data as JToken;
                AppSetting.a.Player += jobject.Value <int>("player");
                AppSetting.a.Row    += jobject.Value <int>("row");
                AppSetting.a.Col    += jobject.Value <int>("col");
            });
            socket.On("EndGame", (data) =>
            {
                var jobject       = data as JToken;
                AppSetting.a.Mes += jobject.Value <String>("message") + "  " + DateTime.Now.ToString() + "\n\n";
            });
        }
        void NewGame()
        {
            string ten = name.Text;

            if (canvas.Children.Count != 0)
                canvas.Children.Clear();
            game = new GomokuViewModel();
            game.Paint_ChessBoard(canvas);

            // mở kết nối
            if (online)
            {
                socket = IO.Socket(Settings.Default.connectStr);
                socket.On(Socket.EVENT_CONNECT, () =>
                {
                    MessageBox.Show( "Connected");
                    socket.Emit("ChatMessage", "hh");
                    socket.Emit("message:" + "hh", "from:" + "hello");
                });
                socket.On(Socket.EVENT_MESSAGE, (data) =>
                {
                    MessageBox.Show(((JObject)data)["message"].ToString());
                });
                socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
                {
                    MessageBox.Show(((JObject)data)["message"].ToString());
                });
                socket.On("ChatMessage", (data) =>
                {
                    if (((JObject)data)["message"].ToString() == "Welcome!")
                    {
                        socket.Emit("MyNameIs", ten);
                        socket.Emit("ConnectToOtherPlayer");
                    }
                    // nhận chat
                    if (data.ToString().Contains("from"))
                    {
                        MessageBox.Show(data.ToString());
                    }
                });
                
                socket.On(Socket.EVENT_ERROR, (data) =>
                {
                    MessageBox.Show(((JObject)data)["message"].ToString());
                });
                socket.On("NextStepIs", (data) =>
                {
                    MessageBox.Show(data.ToString());
                });
            }
        }
        private void sendMessage(String msg)
        {
            if (socket != null)
            {
                MessageConvert messageObj = new MessageConvert();

                messageObj.usr = Environment.UserDomainName + "/" + Environment.UserName;
                messageObj.msg = msg;

                JObject json = JObject.FromObject(messageObj);

                socket.Emit("new message", json);
            }
        }
Exemple #8
0
        public static void KetNoi(Quobject.SocketIoClientDotNet.Client.Socket socket, string name)
        {
            //Việc cần làm: Kết nối tới server, thành công đăng kí danh tính MyNameIs, và ConnectToOtherPlayer
            //Đồng thời khởi tạo cái socket.On() để bắt tương ứng các nội dung
            //Bắt ChatMessage
            //Bắt EndGame
            //Bắt NextStepIs
            //Thất bại(Không kết tới server thành công) xuất thông báo và return
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                MessageBox.Show("Connected", "Thông báo", MessageBoxButton.OK);
            });
            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                MessageBox.Show(data.ToString());
            });

            socket.On("ChatMessage", (data) =>
            {
                string s = "You are the first player!";
                turn     = data.ToString().Contains(s);
                MessageBox.Show(data.ToString());
                if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() == "Welcome!")
                {
                    socket.Emit("MyNameIs", name);
                    socket.Emit("ConnectToOtherPlayer");
                    _name = name;
                }
                else if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() != "Welcome!")
                {
                    _mes = data.ToString();
                }
            });
            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                MessageBox.Show(data.ToString());
            });
            socket.On("NextStepIs", (data) =>
            {
                var a = JObject.Parse(data.ToString());

                _row = (int)a["row"];
                _col = (int)a["col"];
            });
            socket.On("EndGame", (data) =>
            {
                MessageBox.Show(data.ToString());
            });
        }
Exemple #9
0
        public void Json10000000CharsTest()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("json10000000chars");
            });

            socket.On("json10000000chars",
                      (data) =>
            {
                log.Info("EVENT_MESSAGE data=" + data);
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = (JObject)events.Dequeue();
            var str = (string)obj["data"];

            Assert.Equal(10000000, str.Length);
        }
Exemple #10
0
        public void BuffAck()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag             = false;

            var exptected = System.Text.Encoding.UTF8.GetBytes("asdfasdf");

            var options = CreateOptions();
            //options.Transports = ImmutableList.Create<string>(Polling.NAME);
            var uri = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("buffack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });

            socket.Emit("buffa", exptected);

            ManualResetEvent.WaitOne();
            //Task.Delay(8000).Wait();
            socket.Close();
            //Task.Delay(4000).Wait();
            Assert.True(Flag);
            log.Info("Finish");
        }
        public void MessageTest()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var count = new[] {0};
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("hi");
            });

            socket.On("hi",
                (data) =>
                {
                    log.Info("EVENT_MESSAGE");
                    events.Enqueue(data);
                    ManualResetEvent.Set();
                });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();
            Assert.AreEqual("more data", (string) obj);
        }
Exemple #12
0
        public void Cookie()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            options.Cookies.Add("connect.sid", "12345");
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("get_cookie");
            });

            socket.On("got_cookie",
                      (data) =>
            {
                log.Info("EVENT_MESSAGE data=" + data);
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            socket.Close();
            var cookie = (string)events.Dequeue();

            Assert.Equal("connect.sid=12345", cookie);
        }
Exemple #13
0
        public void ShouldReceiveDateWithAckAsAction()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            Message          = "";
            Number           = 0;
            ManualResetEvent = new ManualResetEvent(false);
            var obj = new JObject();

            obj["b"] = true;

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.Emit("getAckDate", (date, n) =>
            {
                log.Info("getAckDate data=" + date);
                Message = ((DateTime)date).ToString("O");
                Number  = int.Parse(n.ToString());
                ManualResetEvent.Set();
            }, obj);


            ManualResetEvent.WaitOne();
            Assert.Equal(28, Message.Length);
            Assert.Equal(5, Number);
            socket.Close();
        }
Exemple #14
0
        public void ShouldWorkWithAcks()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);


            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.Emit("ack");

            socket.On("ack", (cb) =>
            {
                var obj  = new JObject();
                obj["b"] = true;
                var iack = (IAck)cb;
                iack.Call(5, obj);
            });

            socket.On("got it",
                      (data) =>
            {
                log.Info("got it");
                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            socket.Close();
        }
Exemple #15
0
        public void ShouldEmitDateInObject()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("takeDateObj", (data) =>
            {
                log.Info("takeDate");
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            socket.Emit("getDateObj");

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = (JObject)events.Dequeue();

            Assert.IsType <JObject>(obj);
            var date = (obj["date"]).Value <DateTime>();

            Assert.IsType <DateTime>(date);
        }
Exemple #16
0
        public void ShouldWorkWithFalse()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                socket.Emit("false");
            });

            socket.On("false",
                      (data) =>
            {
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();

            Assert.False((bool)obj);
        }
Exemple #17
0
        public void ShouldGetBinaryDataAsAnArraybuffer()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("doge", (data) =>
            {
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            socket.Emit("doge");

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();

            var binData   = (byte[])events.Dequeue();
            var exptected = System.Text.Encoding.UTF8.GetBytes("asdfasdf");
            var i         = 0;

            foreach (var b in exptected)
            {
                Assert.Equal(b, binData[i++]);
            }
        }
Exemple #18
0
        public void MessageTest()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("hi");
            });

            socket.On("hi",
                      (data) =>
            {
                log.Info("EVENT_MESSAGE");
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();

            Assert.Equal("more data", obj);
        }
        public void OgsMessageTest()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("parser_error#21");
            });

            socket.On("parser_error#21_response",
                (data) =>
                {
                    log.Info("EVENT_MESSAGE");
                    events.Enqueue(data);
                    ManualResetEvent.Set();
                });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();
            Assert.Equal("{\"handicap\":0,\"disable_analysis\":false,\"private\":false,\"height\":19,\"time_control\":{\"time_control\":\"byoyomi\",\"period_time\":45,\"main_time\":1800,\"periods\":5},\"ranked\":false,\"meta_groups\":[132,3,196,261,327,489,43,418,302,463,242,403,425,24,25,154,28,157],\"komi\":6.5,\"game_id\":1333070,\"width\":19,\"rules\":\"japanese\",\"black_player_id\":71283,\"white_player_id\":78080,\"players\":{\"white\":{\"username\":\"Rvzy\",\"egf\":501.413,\"rank\":14,\"id\":78080,\"accepted_stones\":\"mcidkdldmdiekeefgfifkfdgegfghgkgfhghhhihkhnhfigihikinifjhjjjkjnjdkekfkgkhkjknkflhljlgmhmimjmgnknlnmnnngo\",\"accepted_strict_seki_mode\":false},\"black\":{\"username\":\"心の光\",\"egf\":353.454,\"rank\":12,\"id\":71283,\"accepted_stones\":\"mcidkdldmdiekeefgfifkfdgegfghgkgfhghhhihkhnhfigihikinifjhjjjkjnjdkekfkgkhkjknkflhljlgmhmimjmgnknlnmnnngo\",\"accepted_strict_seki_mode\":false}},\"game_name\":\"Friendly Match\",\"phase\":\"finished\",\"history\":[],\"initial_player\":\"black\",\"moves\":\"pddpppddfqfocqdjcpcodqepeqncqfkcfcgdcccddcfdecgcgbhbfahcbdbebccfpjnpqnjphphoioipgohngngphqfpgmilcndnbocmdoengqeocodlgkijhiiihhjgifighghfhkikekejfjelflfihjgihminimjnjmkmjlkljkkkjjliihjikjljkijhkhlgkgjfiejegfheidickfmekejdhllhfgehegdhfhedghffeffedgcgdkckfkcibmclblbkldlcmdndmcmbkdjcaeafadnfknjolnlplkllmkmmmnnmnnnkmjnjminimhnhmglfnlomolonmloonglmiqjqjrkrirmfofpbqcorproqpqopplpmqmpoqoosqppsqrqsrrrsoeneodwO6obqblaocnbpaoaqaksjsakalhafbsssr....\",\"allow_self_capture\":false,\"automatic_stone_removal\":false,\"free_handicap_placement\":false,\"allow_ko\":false,\"allow_superko\":true,\"superko_algorithm\":\"ssk\",\"score_territory\":true,\"score_territory_in_seki\":false,\"score_stones\":false,\"score_prisoners\":true,\"score_passes\":true,\"white_must_pass_last\":false,\"opponent_plays_first_after_resume\":true,\"strict_seki_mode\":false,\"initial_state\":{\"black\":\"\",\"white\":\"\"},\"start_time\":1420522348,\"clock\":{\"game_id\":1333070,\"current_player\":78080,\"black_player_id\":71283,\"white_player_id\":78080,\"title\":\"Friendly Match\",\"last_move\":1420524830517,\"expiration\":1420525270589,\"black_time\":{\"thinking_time\":909.8829999999991,\"periods\":5,\"period_time\":45},\"white_time\":{\"thinking_time\":215.07199999999966,\"periods\":5,\"period_time\":45},\"pause_delta\":-517,\"expiration_delta\":440072,\"now\":1420524830517,\"paused_since\":1420524830},\"pause_control\":{\"stone-removal\":true},\"paused_since\":1420524830,\"removed\":\"mcidkdldmdiekeefgfifkfdgegfghgkgfhghhhihkhnhfigihikinifjhjjjkjnjdkekfkgkhkjknkflhljlgmhmimjmgnknlnmnnngo\",\"auto_scoring_done\":true,\"score\":{\"white\":{\"total\":154.5,\"stones\":0,\"territory\":101,\"prisoners\":47,\"scoring_positions\":\"iajakaibjbkblbmanamckdldmdcedeeegekeledfefgfkfdgegfggghgkgfhghhhihkhdieifigihikifjgjhjjjkjdkekfkgkhkjkflglhljldmemfmgmhmimjmfngngohdidieifbfagbgahbhchaibiajbjcjknlnmnnnkolomonokpmpkqlqmqnqlrmrnrlsmsnsio\",\"handicap\":0,\"komi\":6.5},\"black\":{\"total\":101,\"stones\":0,\"territory\":94,\"prisoners\":7,\"scoring_positions\":\"aabacadaeaabbbcbdbebacrasarbsbrcscqdrdsdpeqeresepfrfsfogpgqgrgsgnhohphqhrhshnioipiqirisinjojqjrjsjnkokpkqkrkskqlrlslrmsmrnsnrosorpspqqrqsqamanbnaoapbpaqbqarbrcrdrerfrgrhrasbscsdsesfsgshsis\",\"handicap\":0,\"komi\":0}},\"winner\":78080,\"outcome\":\"53.5 points\",\"end_time\":1420524844}", obj);
        }
Exemple #20
0
        public void ShouldEmitDateAsDate()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("takeDate", (data) =>
            {
                log.Info("takeDate");
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            socket.Emit("getDate");

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();

            Assert.IsInstanceOfType(obj, typeof(DateTime));
        }
Exemple #21
0
        public void ShouldSendBinaryDataAsAnArraybuffer()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag             = false;

            var exptected = System.Text.Encoding.UTF8.GetBytes("asdfasdf");

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("buffack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });

            socket.Emit("buffa", exptected);

            ManualResetEvent.WaitOne();
            socket.Close();
            Assert.True(Flag);
        }
Exemple #22
0
        public void OgsMessageTest()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var options = CreateOptions();
            var uri     = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("parser_error#21");
            });

            socket.On("parser_error#21_response",
                      (data) =>
            {
                log.Info("EVENT_MESSAGE");
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();

            Assert.Equal("{\"handicap\":0,\"disable_analysis\":false,\"private\":false,\"height\":19,\"time_control\":{\"time_control\":\"byoyomi\",\"period_time\":45,\"main_time\":1800,\"periods\":5},\"ranked\":false,\"meta_groups\":[132,3,196,261,327,489,43,418,302,463,242,403,425,24,25,154,28,157],\"komi\":6.5,\"game_id\":1333070,\"width\":19,\"rules\":\"japanese\",\"black_player_id\":71283,\"white_player_id\":78080,\"players\":{\"white\":{\"username\":\"Rvzy\",\"egf\":501.413,\"rank\":14,\"id\":78080,\"accepted_stones\":\"mcidkdldmdiekeefgfifkfdgegfghgkgfhghhhihkhnhfigihikinifjhjjjkjnjdkekfkgkhkjknkflhljlgmhmimjmgnknlnmnnngo\",\"accepted_strict_seki_mode\":false},\"black\":{\"username\":\"心の光\",\"egf\":353.454,\"rank\":12,\"id\":71283,\"accepted_stones\":\"mcidkdldmdiekeefgfifkfdgegfghgkgfhghhhihkhnhfigihikinifjhjjjkjnjdkekfkgkhkjknkflhljlgmhmimjmgnknlnmnnngo\",\"accepted_strict_seki_mode\":false}},\"game_name\":\"Friendly Match\",\"phase\":\"finished\",\"history\":[],\"initial_player\":\"black\",\"moves\":\"pddpppddfqfocqdjcpcodqepeqncqfkcfcgdcccddcfdecgcgbhbfahcbdbebccfpjnpqnjphphoioipgohngngphqfpgmilcndnbocmdoengqeocodlgkijhiiihhjgifighghfhkikekejfjelflfihjgihminimjnjmkmjlkljkkkjjliihjikjljkijhkhlgkgjfiejegfheidickfmekejdhllhfgehegdhfhedghffeffedgcgdkckfkcibmclblbkldlcmdndmcmbkdjcaeafadnfknjolnlplkllmkmmmnnmnnnkmjnjminimhnhmglfnlomolonmloonglmiqjqjrkrirmfofpbqcorproqpqopplpmqmpoqoosqppsqrqsrrrsoeneodwO6obqblaocnbpaoaqaksjsakalhafbsssr....\",\"allow_self_capture\":false,\"automatic_stone_removal\":false,\"free_handicap_placement\":false,\"allow_ko\":false,\"allow_superko\":true,\"superko_algorithm\":\"ssk\",\"score_territory\":true,\"score_territory_in_seki\":false,\"score_stones\":false,\"score_prisoners\":true,\"score_passes\":true,\"white_must_pass_last\":false,\"opponent_plays_first_after_resume\":true,\"strict_seki_mode\":false,\"initial_state\":{\"black\":\"\",\"white\":\"\"},\"start_time\":1420522348,\"clock\":{\"game_id\":1333070,\"current_player\":78080,\"black_player_id\":71283,\"white_player_id\":78080,\"title\":\"Friendly Match\",\"last_move\":1420524830517,\"expiration\":1420525270589,\"black_time\":{\"thinking_time\":909.8829999999991,\"periods\":5,\"period_time\":45},\"white_time\":{\"thinking_time\":215.07199999999966,\"periods\":5,\"period_time\":45},\"pause_delta\":-517,\"expiration_delta\":440072,\"now\":1420524830517,\"paused_since\":1420524830},\"pause_control\":{\"stone-removal\":true},\"paused_since\":1420524830,\"removed\":\"mcidkdldmdiekeefgfifkfdgegfghgkgfhghhhihkhnhfigihikinifjhjjjkjnjdkekfkgkhkjknkflhljlgmhmimjmgnknlnmnnngo\",\"auto_scoring_done\":true,\"score\":{\"white\":{\"total\":154.5,\"stones\":0,\"territory\":101,\"prisoners\":47,\"scoring_positions\":\"iajakaibjbkblbmanamckdldmdcedeeegekeledfefgfkfdgegfggghgkgfhghhhihkhdieifigihikifjgjhjjjkjdkekfkgkhkjkflglhljldmemfmgmhmimjmfngngohdidieifbfagbgahbhchaibiajbjcjknlnmnnnkolomonokpmpkqlqmqnqlrmrnrlsmsnsio\",\"handicap\":0,\"komi\":6.5},\"black\":{\"total\":101,\"stones\":0,\"territory\":94,\"prisoners\":7,\"scoring_positions\":\"aabacadaeaabbbcbdbebacrasarbsbrcscqdrdsdpeqeresepfrfsfogpgqgrgsgnhohphqhrhshnioipiqirisinjojqjrjsjnkokpkqkrkskqlrlslrmsmrnsnrosorpspqqrqsqamanbnaoapbpaqbqarbrcrdrerfrgrhrasbscsdsesfsgshsis\",\"handicap\":0,\"komi\":0}},\"winner\":78080,\"outcome\":\"53.5 points\",\"end_time\":1420524844}", obj);
        }
Exemple #23
0
 public static void GuiToaDo(Quobject.SocketIoClientDotNet.Client.Socket socket, int row, int col)
 {
     socket.On(Socket.EVENT_ERROR, (data) =>
     {
         MessageBox.Show(data.ToString());
     });
     socket.Emit("MyStepIs", JObject.FromObject(new { row = row, col = col }));
 }
 public static void registerClient()
 {
     _socket = IO.Socket(HostURL);            
     if (MediateClass.UserVM.UserInfo != null)
     {
         _socket.Emit("storeMyID", MediateClass.UserVM.UserInfo.UserId);
     }
 }
Exemple #25
0
 public static void GuiToaDo(Quobject.SocketIoClientDotNet.Client.Socket socket, int row, int col)
 {
     //Thực hiện gửi vị trí đánh cho server đầu vào là hàng cột,
     socket.On(Socket.EVENT_ERROR, (data) =>
     {
         MessageBox.Show(data.ToString());
     });
     socket.Emit("MyStepIs", JObject.FromObject(new { row = row, col = col }));
 }
Exemple #26
0
        public void Init()
        {
            machine.client       = "Machine";
            machine.ScreenHeight = "0";
            machine.ScreenWidth  = "0";

            socket.On("connect", () =>
            {
                socket.Emit("init", machine);
                socket.On("init", ServerInit);
            });
            socket.On("disconnect", () =>
            {
                window.Dispatcher.BeginInvoke((Action)(() =>
                {
                    window.Disconnect();
                }));
            });
        }
Exemple #27
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            loggingEvent.Fix = this.Fix;
            //ManualResetEvent ManualResetEvent = null;
            Quobject.SocketIoClientDotNet.Client.Socket socket = IO.Socket(m_serverUrl); //new Client(m_serverUrl);
            ManualResetEvent ManualResetEvent = new ManualResetEvent(false);

            string output = JsonConvert.SerializeObject(new
            {
                HostName        = Environment.MachineName,
                LoggrName       = loggingEvent.LoggerName,
                Level           = loggingEvent.Level.DisplayName,
                Message         = loggingEvent.RenderedMessage,
                ThreadName      = loggingEvent.ThreadName,
                TimeStamp       = loggingEvent.TimeStamp,
                ClassName       = loggingEvent.LocationInformation.ClassName,
                FileName        = loggingEvent.LocationInformation.FileName,
                LineNumber      = loggingEvent.LocationInformation.LineNumber,
                MethodName      = loggingEvent.LocationInformation.MethodName,
                StackFrames     = loggingEvent.LocationInformation.StackFrames,
                UserName        = loggingEvent.UserName,
                ExceptionString = loggingEvent.GetExceptionString(),
                Domain          = loggingEvent.Domain,
                Identity        = loggingEvent.Identity,
                Propeties       = loggingEvent.Properties
            }, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings
            {
                CheckAdditionalContent     = true,
                ConstructorHandling        = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor,
                MetadataPropertyHandling   = Newtonsoft.Json.MetadataPropertyHandling.ReadAhead,
                MissingMemberHandling      = Newtonsoft.Json.MissingMemberHandling.Ignore,
                NullValueHandling          = Newtonsoft.Json.NullValueHandling.Include,
                ObjectCreationHandling     = Newtonsoft.Json.ObjectCreationHandling.Reuse,
                PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All,
                ReferenceLoopHandling      = Newtonsoft.Json.ReferenceLoopHandling.Serialize
            });
            JObject jobj = JObject.Parse(output);

            try
            {
                socket.On(Socket.EVENT_CONNECT, () =>
                {
                    //socket.Emit("nickname", Environment.MachineName);
                    socket.Emit("sendMessage", jobj);
                    ManualResetEvent.Set();
                });
                ManualResetEvent.WaitOne(5000, true);
                socket.Disconnect();
                socket.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("<<<< WebSocketAppender ERROR >>>> {0}", ex.ToString());
            }
        }
Exemple #28
0
        public WebSocket()
        {
            if (string.IsNullOrEmpty(Properties.Settings.Default.WebSocketUrl))
            {
                new ArgumentNullException("WebSocket URLが設定されていません。");
            }

            var options = new IO.Options();

            //// JWT Token
            //if (Model.WebAPI != null && !string.IsNullOrEmpty(Model.WebAPI.token))
            //{
            //    options.ExtraHeaders.Add("Authorization", string.Format("Bearer {0}", Model.WebAPI.token));
            //}

            socket = IO.Socket(Properties.Settings.Default.WebSocketUrl, options);

            socket.On(Socket.EVENT_CONNECT, (data) =>
            {
                logger.Debug($"EVENT_CONNECT {data}");

                JObject jout = JObject.FromObject(new { channel = "BroadcastChannel" });

                socket.Emit("subscribe", jout);
            });

            socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
            {
                logger.Debug($"EVENT_CONNECT_ERROR {data}");
            });

            socket.On(Socket.EVENT_CONNECT_TIMEOUT, (data) =>
            {
                logger.Debug($"EVENT_CONNECT_TIMEOUT {data}");
            });

            socket.On(Socket.EVENT_DISCONNECT, (data) =>
            {
                logger.Debug($"EVENT_DISCONNECT {data}");
            });

            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                logger.Debug($"EVENT_ERROR {data}");
            });

            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                logger.Debug($"EVENT_MESSAGE {data}");
            });

            // プレゼンス情報の更新イベント
            socket.On("App\\Events\\PresenceUpdated", new PresenceUpdateEvent(this));
        }
Exemple #29
0
        public void ShouldReceiveUtf8MultibyteCharacters()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue <object>();

            var correct = new string[]
            {
                "てすと",
                "Я Б Г Д Ж Й",
                "Ä ä Ü ü ß",
                "utf8 — string",
                "utf8 — string"
            };
            var i = 0;

            var options = CreateOptions();

            options.Transports = new List <string>()
            {
                "polling"
            };
            var uri = CreateUri();

            socket = IO.Socket(uri, options);

            socket.On("takeUtf8", (data) =>
            {
                events.Enqueue(data);
                i++;
                log.Info(string.Format("takeUtf8 data={0} i={1}", (string)data, i));

                if (i >= correct.Length)
                {
                    ManualResetEvent.Set();
                }
            });


            socket.Emit("getUtf8");
            ManualResetEvent.WaitOne();
            socket.Close();
            var j = 0;

            foreach (var obj in events)
            {
                var str = (string)obj;
                Assert.Equal(correct[j++], str);
            }
        }
Exemple #30
0
        public static void connect(string ip = "http://localhost:8080")
        {
            if (SocketConnected == false)
            {
                socket          = IO.Socket(ip);
                SocketConnected = true;
            }
            socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT, () =>
            {
                socket.Emit("createRoom", "TH");
            });

            socket.On("created", (data) =>
            {
                MessageBox.Show("Khởi tạo kết nối thành công!");
            });

            socket.On("exist", (data) =>
            {
                join();
            });
        }
 public static void ReadSerial()
 {
     while (true)
     {
         buffer = string.Empty;
         string data = port.ReadLine();
         if (data.Length == 12)
         {
             Console.WriteLine(data);
             socket.Emit("CTN", data);
         }
     }
 }
Exemple #32
0
        public static void SendMessage(string to, WtMessage.ToType toType, string msg, WtMessage.MessageType messageType)
        {
            var obj = JObject.FromObject(new
            {
                fromType = WtMessage.FromType.User,
                from     = MainViewModel.Me.Id,
                to,
                toType,
                messageType,
                client   = Client.Win8,
                markdown = 1,
                content  = msg
            });

            _socket.Emit("message", obj);
        }
Exemple #33
0
        public void ShouldSendBinaryDataAsAnArraybufferMixedWithJson()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag             = false;

            var buf  = System.Text.Encoding.UTF8.GetBytes("howdy");
            var jobj = new JObject();

            jobj.Add("hello", "lol");
            jobj.Add("message", buf);
            jobj.Add("goodbye", "gotcha");

            var options = CreateOptions();
            //options.Transports = ImmutableList.Create<string>(Polling.NAME);

            var uri = CreateUri();

            socket = IO.Socket(uri, options);
            socket.On("jsonbuff-ack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                log.Info("EVENT_DISCONNECT");
            });

            socket.Emit("jsonbuff", jobj);

            ManualResetEvent.WaitOne();
            Task.Delay(1).Wait();

            log.Info("About to wait 1sec");

            //Task.Delay(1000).Wait();
            log.Info("About to call close");
            socket.Close();
            //Task.Delay(1000).Wait();
            Assert.True(Flag);
            log.Info("Finish");
        }
        public void Login(string username)
        {
            if (socket != null)
            {
                socket.Close();
            }

            socket = IO.Socket("http://chat.socket.io/");
            socket.Connect();

            var alert = new AlertDialog.Builder(this).SetMessage("Logging in...").Show();
            var chat = new ChatFragment(username, socket, alert);
            FragmentManager.BeginTransaction()
                           .Replace(Resource.Id.frameLayout, chat)
                           .Commit();

            // Tell the server your username (login)
            socket.Emit("add user", username);
        }
Exemple #35
0
    // Update is called once per frame
    void Update()
    {
        double x = gameObject.transform.eulerAngles.x;
        double y = gameObject.transform.eulerAngles.y;
        double z = gameObject.transform.eulerAngles.z;

        double vertical = x;

        if (x < 180)
        {
            vertical = (-1 * (x / 18));
        }
        else
        {
            vertical = (1 - ((x - 270) / 90));
        }

        vertical = Math.Round(vertical, 2);
        vertical = Math.Min(vertical, 1.00);
        vertical = Math.Max(vertical, -1.00);

        double horizontal = y;

        if (y < 180)
        {
            horizontal = (y / 90);
        }
        else
        {
            horizontal = (-1 - (-1 * ((y - 270) / 90)));
        }

        horizontal = Math.Round(horizontal, 2);
        horizontal = Math.Min(horizontal, 1.00);
        horizontal = Math.Max(horizontal, -1.00);

        var data = "{\"horizontal\": " + (-1 * horizontal) + ", \"vertical\": " + vertical + "}";

        Debug.Log(data);

        socket.Emit("headset position", JsonConvert.SerializeObject(data));
    }
Exemple #36
0
        public static void SocketInit()
        {
            socket = IO.Socket(Config.apiBase);
            socket.Emit("login", Config.UserPhone);
            //socket.On("chat", (data) =>
            //{
            //    string str = data.ToString();
                
            //    MessageModel messageModel = JsonConvert.DeserializeObject<MessageModel>(str);
            //    DbService.Current.Add(messageModel);
            //    UserModel chatUser = new UserModel
            //    {
            //        uid = messageModel.myPhone,
            //        name = messageModel.myName,
            //        image = messageModel.myImage,
            //        dream = messageModel.myDream,
            //        isRead = false
            //    };
            //    DbService.Current.InsertOrUpdateFalse(chatUser);
            //    switch (messageModel.type)
            //    {
            //        case 0:
            //            ToastNotify.Notify("私信  "+messageModel.myName + ":" + messageModel.msg);
            //            break;
            //        case 1:
            //            ToastNotify.Notify("私信  " + messageModel.myName + "向您发送一段了语音");
            //            break;
            //        case 2:
            //            ToastNotify.Notify("私信  " + messageModel.myName + "向您发送了一张图片");
            //            break;
            //        default:
            //            break;

            //    }

            //});
            
            
        }
        public void ShouldReceiveDateWithAckAsAction()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            Message = "";
            Number = 0;
            ManualResetEvent = new ManualResetEvent(false);
            var obj = new JObject();
            obj["b"] = true;

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.Emit("getAckDate", (date, n) =>
            {
                log.Info("getAckDate data=" + date);
                Message = ((DateTime)date).ToString("O");
                Number = int.Parse(n.ToString());
                ManualResetEvent.Set();
            }, obj);


            ManualResetEvent.WaitOne();
            Assert.Equal(28, Message.Length);
            Assert.Equal(5, Number);
            socket.Close();
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			if (socket != null) {
				socket.Close ();
			}

			socket = IO.Socket ("http://chat.socket.io/");
			socket.Connect ();

			var alert = new UIAlertView ("Log in", "Logging in...", null, null, null);
			alert.Show ();

			AttachSocketEvents (alert);

			// Tell the server your username (login)
			socket.Emit ("add user", Username);

			entryText.Selected = true;
			entryText.Started += (sender, e) => {
				if (connected) {
					if (!typing) {
						typing = true;
						socket.Emit ("typing");
					}
				}
			};
			entryText.Ended += (sender, e) => {
				if (connected) {
					if (typing) {
						socket.Emit ("stop typing");
						typing = false;
					}
				}
			};
			sendButton.TouchUpInside += (sender, e) => {
				SendMessage ();
				socket.Emit ("stop typing");
				typing = false;
			};

			// scroll up when the keyboard appears
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, notification => {
				var info = notification.UserInfo;
				var kbFrame = (NSValue)info [UIKeyboard.FrameEndUserInfoKey];
				var kbDuration = (NSNumber)info [UIKeyboard.AnimationDurationUserInfoKey];
				var animationDuration = kbDuration.DoubleValue;
				var keyboardFrame = kbFrame.CGRectValue;

				nfloat height = keyboardFrame.Size.Height + 8;

				entryTextBottom.Constant = height;
				sendButtonBottom.Constant = height;

				UIView.Animate (animationDuration, () => View.LayoutIfNeeded ());
			});
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, notification => {
				var info = notification.UserInfo;
				var kbDuration = (NSNumber)info [UIKeyboard.AnimationDurationUserInfoKey];
				var animationDuration = kbDuration.DoubleValue;

				entryTextBottom.Constant = 8;
				sendButtonBottom.Constant = 8;

				UIView.Animate (animationDuration, () => View.LayoutIfNeeded ());
			});
		}
        public void ShouldWorkWithAcks2()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            string message = "";

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.Emit("ack2");

            var myIListenerImpl = new Acks2ListenerImpl((msg, cb) =>
            {
                message = (string)msg;
                var obj = new JObject();
                obj["b"] = true;
                var iack = (IAck)cb;
                iack.Call(5, obj);

            });


            socket.On("ack2", myIListenerImpl);

            socket.On("got it",
                (data) =>
                {
                    log.Info("got it");
                    ManualResetEvent.Set();
                });

            ManualResetEvent.WaitOne();
            Assert.Equal("hello there", message);
            socket.Close();

        }
        public void ShouldEmitDateAsDate()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("takeDate", (data) =>
            {
                log.Info("takeDate");
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            socket.Emit("getDate");

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();
            Assert.IsInstanceOfType(obj, typeof(DateTime) );
        }
        public void ShouldSendBinaryDataAsAnArraybuffer()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag = false;

            var exptected = System.Text.Encoding.UTF8.GetBytes("asdfasdf");

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("buffack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });

            socket.Emit("buffa", exptected);

            ManualResetEvent.WaitOne();
            socket.Close();
            Assert.True(Flag);
        }
        public void ShouldEmitDateInObject()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("takeDateObj", (data) =>
            {
                log.Info("takeDate");
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            socket.Emit("getDateObj");

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = (JObject) events.Dequeue();

            Assert.IsType<JObject>(obj);
            var date = (obj["date"]).Value<DateTime>();
            Assert.IsType<DateTime>(date);
        }
Exemple #43
0
        public void ListenData()
        {
            string serverAddress = ConfigurationManager.AppSettings["ServerAddress"];
            socket = IO.Socket(serverAddress);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Dispatcher.Invoke(() =>
                {
                });
            });
            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                Dispatcher.Invoke(() =>
                {
                    rtb_conversation.AppendText(((Newtonsoft.Json.Linq.JObject)data).ToString() + Environment.NewLine);
                });
            });
            socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
            {
                if (!isError)
                {
                    Dispatcher.Invoke(() =>
                    {
                        rtb_conversation.AppendText("Cannot connect to SERVER" + Environment.NewLine);
                    });
                    isError = true;
                }
            });

            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                Dispatcher.Invoke(() =>
                {
                    rtb_conversation.AppendText(((Newtonsoft.Json.Linq.JObject)data).ToString() + Environment.NewLine);
                });
            });


            socket.On("ChatMessage", (data) =>
            {
                string message = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                string timeNow = DateTime.Now.ToString("HH:mm:ss tt");

                if (message == "Welcome!")
                {
                    Dispatcher.Invoke(() =>
                    {
                        rtb_conversation.AppendText(string.Format("Server - {0}", DateTime.Now.ToString("HH:mm:ss tt")) + Environment.NewLine);
                        rtb_conversation.AppendText(string.Format("{0}", message) + Environment.NewLine);
                        rtb_conversation.AppendText("--------------------------------------------------------" + Environment.NewLine);
                    });

                    if (playerName != "Guest")
                    {
                        socket.Emit("MyNameIs", playerName);
                    }
                    socket.Emit("ConnectToOtherPlayer");

                }
                //Message which annouces player connect to server and recieve turn
                else if (message.Contains("<br />"))
                {
                    int index = message.IndexOf("<br />");
                    string str1 = message.Substring(0, index);
                    string str2 = message.Substring(index + 6);
                    Dispatcher.Invoke(() =>
                    {
                        rtb_conversation.AppendText(string.Format("Server - {0}", DateTime.Now.ToString("HH:mm:ss tt")) + Environment.NewLine);
                        rtb_conversation.AppendText(str1 + Environment.NewLine);
                        rtb_conversation.AppendText(str2 + Environment.NewLine);
                        rtb_conversation.AppendText("--------------------------------------------------------" + Environment.NewLine);
                        rtb_conversation.ScrollToEnd();
                    });
                    //If BOT online and have first turn, lets it plays at [5,5]
                    if (ChosingMode.mode == 4)
                    {
                        socket.Emit("ChatMessage", botChat[0]);
                        if (str2 != "You are the second player!")
                        {
                            choosedRow = 5;
                            choosedCol = 5;
                            socket.Emit("MyStepIs", JObject.FromObject(new { row = 5, col = 5 }));
                        }
                    }

                }
                //Message from other player
                else if (((Newtonsoft.Json.Linq.JObject)data).Count > 1)
                {
                    Dispatcher.Invoke(() =>
                    {
                        rtb_conversation.AppendText(string.Format("{0} - {1}", ((Newtonsoft.Json.Linq.JObject)data)["from"].ToString(), DateTime.Now.ToString("HH:mm:ss tt")) + Environment.NewLine);
                        rtb_conversation.AppendText(string.Format("{0}", message) + Environment.NewLine);
                        rtb_conversation.AppendText("--------------------------------------------------------" + Environment.NewLine);
                        rtb_conversation.ScrollToEnd();
                    });
                }
                //Message from server
                else
                {
                    Dispatcher.Invoke(() =>
                    {
                        rtb_conversation.AppendText(string.Format("Server - {0}", DateTime.Now.ToString("HH:mm:ss tt")) + Environment.NewLine);
                        rtb_conversation.AppendText(string.Format("{0}", message) + Environment.NewLine);
                        rtb_conversation.AppendText("--------------------------------------------------------" + Environment.NewLine);
                        rtb_conversation.ScrollToEnd();
                    });
                }
            });

            //End of round
            socket.On("EndGame", (data) =>
            {
                Dispatcher.Invoke(() =>
                {
                    string message = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                    rtb_conversation.AppendText(string.Format("Server - {0}", DateTime.Now.ToString("HH:mm:ss tt")) + Environment.NewLine);
                    rtb_conversation.AppendText(string.Format("{0}", message) + Environment.NewLine);
                    rtb_conversation.AppendText("--------------------------------------------------------" + Environment.NewLine);
                    rtb_conversation.ScrollToEnd();
                    MessageBox.Show(message);
                    thread.Interrupt();
                    socket.Close();
                    this.Close();
                });
            });


            //Recieve game info
            socket.On("NextStepIs", (data) =>
            {
                int player = int.Parse(((Newtonsoft.Json.Linq.JObject)data)["player"].ToString()) + 1;
                int row = int.Parse(((Newtonsoft.Json.Linq.JObject)data)["row"].ToString());
                int col = int.Parse(((Newtonsoft.Json.Linq.JObject)data)["col"].ToString());
                //player = 1: client turn
                if (player == 1)
                {
                    Dispatcher.Invoke(() =>
                    {
                        btnList[row][col].Content = AddChess(row, col, player);
                        gp.board[row, col] = player;                      
                    });
                }
                //player = 2 other turn
                else
                {
                    Dispatcher.Invoke(() =>
                    {
                        btnList[row][col].Content = AddChess(row, col, player);
                        gp.board[row, col] = player;                        
                    });
                    if (ChosingMode.mode == 4)
                        {
                            Thread aiThread = new Thread(new ThreadStart(gp.ChooseChess));
                            aiThread.Start();
                            Thread.Sleep(10);
                            choosedCol = gp.col;
                            choosedRow = gp.row;
                            gp.board[choosedRow, choosedCol] = 2;
                            socket.Emit("MyStepIs", JObject.FromObject(new { row = choosedRow, col = choosedCol }));
                            socket.Emit("ChatMessage", botChat[rd.Next(1, botChat.Count())] );
                        }
                    
                }
            });
        }
        private void myWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            String ServerName = ConfigurationManager.ConnectionStrings["ServerName"].ConnectionString;
            socket = IO.Socket(ServerName);
            while(connected == false)
            {
                socket.On(Socket.EVENT_CONNECT, () =>
                {
                    connected = true;
                });
            }

            socket.On("ChatMessage", (data) =>
            {
                //var jobject = data as JToken;
                //message = jobject.Value<String>("message");
                message = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();

                if (binding.TextChat == message)
                {
                    binding.TextChat = message + "<next>";
                }
                else
                {
                    binding.TextChat = message;
                }
                
                //MessageBox.Show(message);
                //OnMessage(message);
                //chatbox.set("aa");

                if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() == "Welcome!")
                {
                    socket.Emit("MyNameIs", namePlayer);
                    socket.Emit("ConnectToOtherPlayer");
                    //MessageBox.Show("ConnecttoOtherPlayer");
                    //Console.ReadKey(intercept: true);
                }

                if (((Newtonsoft.Json.Linq.JObject)data).Count == 2)
                {
                    name = ((Newtonsoft.Json.Linq.JObject)data)["from"].ToString() ;
                }
                else
                {
                    name = "SERVER";
                }

                if (isCheckTurn == false)
                {
                    string[] tokens = message.Split(new[] { "<br />" }, StringSplitOptions.None);

                    if (tokens.Length < 2)
                        return;

                    /*for (int i = 0; i < tokens.Length; i++)
                        MessageBox.Show(tokens[i]);*/


                    if (tokens[1] == "You are the first player!")
                    {
                        board.Onlineturn = 1;
                        isCheckTurn = true;
                        MessageBox.Show("You are the FIRST player!");
                        if (Board.PropertyMode == 4)
                        {
                            Point temp = new Point(-2, -2);
                            binding.Pos = temp;
                        }
                    }
                    else if (tokens[1] == "You are the second player!")
                    {
                        board.Onlineturn = 2;
                        isCheckTurn = true;
                        MessageBox.Show("You are the SECOND player!");
                    }
                }
            });

            socket.On("NextStepIs", (data) =>
            {
                //Console.WriteLine("NextStepIs: " + data);
                var nextStep = data as JToken;
                //int x = nextStep.Value<int>("row");
                //int y = nextStep.Value<int>("col");
                if (nextStep.Value<int>("player") == 1)
                {
                    Point temp = new Point();
                    temp.X = nextStep.Value<int>("row");
                    temp.Y = nextStep.Value<int>("col");
                    binding.Pos = temp;
                    //btnplay_Click((object)btnplay, RoutedEventArgs.Empty);
                    //pos.Pos = temp;
                    //MessageBox.Show(Pos.ToString());
                }
            });

            socket.On("EndGame", (data) =>
            {
                binding.IsOnlineWin = 1;
                message = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                binding.TextChat = message;
            });
        }
        public void BuffAck()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag = false;

            var exptected = System.Text.Encoding.UTF8.GetBytes("asdfasdf");

            var options = CreateOptions();
            //options.Transports = ImmutableList.Create<string>(Polling.NAME);
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("buffack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });

            socket.Emit("buffa", exptected);

            ManualResetEvent.WaitOne();
            //Task.Delay(8000).Wait();
            socket.Close();
            //Task.Delay(4000).Wait();
            Assert.True(Flag);
            log.Info("Finish");
        }
        /// <summary>
        /// Kết nối
        /// </summary>
        private void connectServer()
        {
            socket = IO.Socket(System.Configuration.ConfigurationSettings.AppSettings["IPConnectGomoku"]);

            socket.On(Socket.EVENT_CONNECT, () =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    lvw_chat.Items.Add("Server: Connected to Server" + getTime());
                }));
            });

            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {

                this.Dispatcher.Invoke((Action)(() =>
                {
                    lvw_chat.Items.Add(data + "");
                }));
            });
            socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {                    
                    lvw_chat.Items.Add("connect Error");
                }));
            });


            socket.On("ChatMessage", (data) =>
            {
                if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() == "Welcome!")
                {
                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        socket.Emit("MyNameIs", user);
                       // socket.Emit("ConnectToOtherPlayer");
                    }));
                }
                else
                {
                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        String name = "";
                        String s = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                        s = strimMes(s);
                        if (name == "")
                            name = "Server: ";
                        else
                            name += ": ";
                        lvw_chat.Items.Add(name + s + getTime());
                    }));
                }

            });
            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    lvw_chat.Items.Add(data + " event error");
                }));
            });
            socket.On("NextStepIs", (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    lock (synch)
                    {
                        int row = (int)((JObject)data).GetValue("row");
                        int col = (int)((JObject)data).GetValue("col");
                        if (checkPoint(col, row))
                        {
                            testshot_online = 3;
                            player_server = new CPlayer(row, col, true, color2, (int)EPlayerFlag.Server);
                            drawGomoku(player_server);
                            if (checkWinner(player_server))
                            {
                                showWinner((int)EPlayerFlag.Server);
                                newGame();
                            }
                            else
                            {
                                //String s = "Your turn!";
                                //lvw_chat.Items.Add(s);
                            }
                            //Tính nước chơi cho COM
                            if (player_pc.State == true)
                            {
                                lock (synch_pc_ol)
                                {
                                    player_pc = findWayforPC(3, 1);
                                    player_pc.ColorPlayer = color1;
                                    player_pc.State = true;
                                    drawGomoku(player_pc);
                                    socket.Emit("MyStepIs", JObject.FromObject(new { row = player_pc.Row, col = player_pc.Column }));
                                    if (checkWinner(player_pc))
                                    {
                                        showWinner((int)EPlayerFlag.Player1);
                                        newGame();
                                    }
                                }
                            }
                        }
                    }
                }));
            });
        }
Exemple #47
0
        public Connection_Sever(string nameHuman)
        {
            m_NameHuman = nameHuman;
            if (m_NameHuman == null)
                m_NameHuman = "Anh Tuấn";
            socket = IO.Socket(Settings.Default.IP);
            socket.On(Socket.EVENT_CONNECT, () => {  });
            // Nhận 
            socket.On(Socket.EVENT_MESSAGE, (data) =>{  });

            // nhận lỗi khi connection từ sever
            socket.On(Socket.EVENT_CONNECT_ERROR, (data) => { });

            // nhận lỗi từ sever
            socket.On(Socket.EVENT_ERROR, (data) => { });


            // nhận thông điệp chat từ sever
            socket.On("ChatMessage", (data) =>
            {
                var jobject = data as JToken;
                string a = jobject.Last.First.ToString(); // tên người gởi
                string b = jobject.First.First.ToString(); // mesage

                // nếu người gởi là sever thì a và b bằng nhau và bằng thông điệp gởi 
                if(a == b && jobject.First.Next == null)
                {
                    m_NameSever = "SEVER";
                    if(message_changed != null)
                        message_changed(b);
                }

                else
                {
                    m_NameSever = a;
                    //m_NamePlayer2 = a;
                    if (message_changed != null)
                        message_changed(b);
                }


                if (((JObject)data)["message"].ToString() == "Welcome!")
                {
                    socket.Emit("MyNameIs", m_NameHuman);
                    socket.Emit("ConnectToOtherPlayer");
                }

                if (jobject.Value<String>("message").IndexOf("first") > 0)
                {
                    m_isFrist = true;
                    m_StartGame = true;
                    if (StartPlayAuToOnline != null)
                        StartPlayAuToOnline(m_isFrist);
                }
                if (jobject.Value<String>("message").IndexOf("second") > 0)
                {
                    m_isFrist = false;
                    m_StartGame = true;
                    if (StartPlayAuToOnline != null)
                        StartPlayAuToOnline(m_isFrist);
                }
            });

            socket.On("EndGame", (data) =>
            {
                string temp = getMessageFromSever(data, "message");
                if (message_changed != null)
                {
                    message_changed(temp);
                }
                if(temp.Contains("won the game!"))
                {
                    string nameWin;
                    if (temp.Contains(m_NameHuman))
                        nameWin = m_NameHuman;
                    else nameWin = m_NameSever;

                    winArray = new List<Point>();
                    List<JToken> listJToken = ((Newtonsoft.Json.Linq.JObject)data)["highlight"].Children().ToList();

                    foreach (JToken re in listJToken)
                    {
                        Point temp1 = new Point();

                        temp1.X = (int)re["row"];
                        temp1.Y = (int)re["col"];
                        winArray.Add(temp1);
                    }
                    if (winGame != null)
                        winGame(winArray, nameWin);
                }

                if (temp.Contains("left the game!"))
                {
                    if (LeftGame != null)
                        LeftGame();
                }
              
            });

        }
        public MainWindow(int typeOption, string namePlayer)
        {
            InitializeComponent();

            // Khởi tạo mảng các ô cờ: Dùng để đánh dấu tình trạng của ô cờ
            for (int i = 0; i < ROW; i++)
                arrSquare[i] = new int[COL];

            SetIsStatic();

            board = new ChessBoard();
            board.ClickSquare += ClickChange;
            DataContext = board;

            userPlayer1.Name = namePlayer;
            type = typeOption;

            showChatMessage("Trò chơi bắt đầu", "System");

            if (type == 2)
            {
                bWorker.DoWork += new DoWorkEventHandler(DoComputer);
                bWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteComputerTurn);
                bWorker.RunWorkerAsync();
            }
            else if (type == 3 || type == 4) // Nếu kiểu chơi là 3 hoăc 4 sẽ tiến hành kết nối Server
            {
                //socket = IO.Socket("ws://gomoku-lajosveres.rhcloud.com:8000");
                socket = IO.Socket(ConfigurationSettings.AppSettings["linkGomoku"]);
                socket.On(Socket.EVENT_CONNECT, () =>
                {
                    Thread t = new Thread(() => showChatMessage("Connected", "System"));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                });

                socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
                {
                    Thread t = new Thread(() => showChatMessage(data.ToString(), "Server"));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                });

                socket.On("ChatMessage", (data) =>
                {
                    Thread t = new Thread(() => showChatMessage(data.ToString(), "Server"));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();

                    if (((Newtonsoft.Json.Linq.JObject)data)["message"].ToString() == "Welcome!")
                    {
                        socket.Emit("MyNameIs", userPlayer1.Name);
                        socket.Emit("ConnectToOtherPlayer");
                    }

                    if (!holdTurn)
                    {
                        if (data.ToString().Contains("first"))
                        {
                            player = true;
                            holdTurn = true;
                            connectSuccess = true;
                        }
                        else if (data.ToString().Contains("second"))
                        {
                            player = false;
                            holdTurn = true;
                            connectSuccess = true;
                        }

                        // Gửi qua bước đi trước
                        if (type == 4 && player && connectSuccess)
                        {
                            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                (ThreadStart)delegate ()
                                {
                                    Random rand = new Random();

                                    do
                                    {
                                        x = rand.Next(0, 11);
                                        y = rand.Next(0, 11);
                                    }
                                    while (arrSquare[x][y] == 2 || arrSquare[x][y] == 3);

                                    arrSquare[x][y] = 2;

                                    board = new ChessBoard(arrSquare);
                                    //board.ClickSquare += ClickChange;
                                    DataContext = board;

                                    // Gửi bước đi lên Server
                                    // Phương thức gửi bước đi của mình lên Server
                                    socket.Emit("MyStepIs", JObject.FromObject(new { row = x, col = y }));

                                    if (IsEndGame(player))
                                    {
                                        //socket.Emit("MyStepIs", JObject.FromObject(new { row = x, col = y })); // 
                                        MessageBox.Show("Bạn đã chiến thắng!", "Thông báo");
                                        return;
                                    }                            

                                    player = false;
                                });
                        }
                    }
                });

                socket.On(Socket.EVENT_ERROR, (data) =>
                {
                    Thread t = new Thread(() => showChatMessage(data.ToString(), "Server"));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                });

                socket.On("NextStepIs", (data) =>
                {
                    Thread t = new Thread(() => showChatMessage(data.ToString(), "Server"));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();

                    string[] partData = data.ToString().Split(',');
                    string[] user = partData[0].Split(' ');
                    if (type != 4)
                    {
                        if (int.Parse(user[3]) == 1)
                        {
                            string[] rowData = partData[1].Split(' ');
                            string[] colData = partData[2].Split(' ');
                            string colDataNum = "";
                            for (int i = 0; i < colData[3].Length; i++)
                            {
                                if (colData[3][i] >= '0' && colData[3][i] <= '9')
                                    colDataNum += colData[3][i];
                                else
                                    break;
                            }

                            rowServer = int.Parse(rowData[3]);
                            colServer = int.Parse(colDataNum);

                            //arrSquare[rowServer][colServer] = 3;

                            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                (ThreadStart)delegate ()
                                {
                                    DoPlayerServer();

                                    if (IsEndGame(player))
                                    {
                                        MessageBox.Show("Người chơi 2 chiến thắng", "Thông báo");
                                        return;
                                    }

                                    if (isFullSquare())
                                    {
                                        MessageBox.Show("Gameover", "Thông báo");
                                        return;
                                    }

                                    player = true;
                                });
                        }
                    }
                    else if (type == 4 && connectSuccess)
                    {
                        if (!player)
                        {
                            if (int.Parse(user[3]) == 1)
                            {
                                string[] rowData = partData[1].Split(' ');
                                string[] colData = partData[2].Split(' ');
                                string colDataNum = "";
                                for (int i = 0; i < colData[3].Length; i++)
                                {
                                    if (colData[3][i] >= '0' && colData[3][i] <= '9')
                                        colDataNum += colData[3][i];
                                    else
                                        break;
                                }

                                rowServer = int.Parse(rowData[3]);
                                colServer = int.Parse(colDataNum);

                                //arrSquare[rowServer][colServer] = 3;

                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                    (ThreadStart)delegate ()
                                    {
                                        DoPlayerServer();

                                        if (IsEndGame(player))
                                        {
                                            MessageBox.Show("Người chơi 2 chiến thắng", "Thông báo");
                                            return;
                                        }

                                        if (isFullSquare())
                                        {
                                            MessageBox.Show("Gameover", "Thông báo");
                                            return;
                                        }

                                        player = true;

                                        DoComputerServer();
                                    });
                            }
                        }
                    }
                });

                //bWorkerServer.DoWork += new DoWorkEventHandler(DoPlayerServer);
                //bWorkerServer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteComputerTurn);
                //bWorkerServer.RunWorkerAsync();
            }
        }
Exemple #49
0
        private void Play_online_Click(object sender, RoutedEventArgs e)
        {
            //var socket = IO.Socket("ws://gomoku-lajosveres.rhcloud.com:8000");
            string connect = ConfigurationManager.ConnectionStrings["LINK_GOMOKU"].ConnectionString;
            socket = IO.Socket(connect);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    message += "\n";
                    message += "connected";
                    ListChat.Text += message;
                    message += "\n";
                }));
            });

            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    mess += data.ToString();
                    ListChat.Text = mess;
                    mess += "\n";
                }));
            });

            socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    mess += data.ToString();
                    ListChat.Text = mess;
                    mess += "\n";
                }));
            });

            socket.On("ChatMessage", (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {                   
                    message = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                    if (message == "Welcome!")
                    {
                        socket.Emit("MyNameIs", name);
                        socket.Emit("ConnectToOtherPlayer");
                        ListChat.Text += "\nServer";
                        ListChat.Text += "\t\t\t";
                        ListChat.Text += DateTime.Now;
                        ListChat.Text += "\n";
                        ListChat.Text += message;
                        ListChat.Text += "\n..........................................................................................\n\n";
                        
                        //mess = "\nServer";
                        //mess = "\t\t\t";
                        //mess = DateTime.Now;
                        //mess = "\n";
                        //mess = message;
                        //mess = "\n..........................................................................................\n\n";
                    }
                    else
                    {
                        if (((Newtonsoft.Json.Linq.JObject)data)["from"] == null)
                        {
                            ListChat.Text += "Server";
                            ListChat.Text += "\t\t\t";
                            ListChat.Text += DateTime.Now;
                            ListChat.Text += "\n";
                            message = XuLy(ref message);
                            ListChat.Text += message;
                            ListChat.Text += "\n.................ab......................................................................\n\n";
                            message += "\n";
                        }
                        else
                            if (((Newtonsoft.Json.Linq.JObject)data)["from"].ToString() != name)
                            {
                                ListChat.Text += ((Newtonsoft.Json.Linq.JObject)data)["from"].ToString();
                                ListChat.Text += "\t\t\t";
                                ListChat.Text += DateTime.Now;
                                ListChat.Text += "\n";
                                //message = XuLy(ref message);
                                ListChat.Text += message;
                                ListChat.Text += "\n.................abc......................................................................\n\n";
                                message += "\n";
                            }
                    }
                }));
                //s = true;
            });
            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    message += data.ToString();
                    ListChat.Text += message;
                    message += "\n";
                }));
            });
        }
        public void ShouldWorkWithFalse()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                socket.Emit("false");
            });

            socket.On("false",
                (data) =>
                {
                    events.Enqueue(data);
                    ManualResetEvent.Set();
                });

            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();
            Assert.False((bool) obj);
        }
        public void ShouldReceiveUtf8MultibyteCharacters()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var correct = new string[]
            {
                "てすと",
                "Я Б Г Д Ж Й",
                "Ä ä Ü ü ß",
                "李O四",
                "utf8 — string"
            };
            var i = 0;

            var options = CreateOptions();
            options.Transports = ImmutableList.Create<string>(Polling.NAME);
            var uri = CreateUri();
            socket = IO.Socket(uri, options);

            socket.On("takeUtf8", (data) =>
            {
                events.Enqueue(data);
                i++;
                log.Info(string.Format("takeUtf8 data={0} i={1}",(string)data,i));

                if (i >= correct.Length)
                {
                    ManualResetEvent.Set();
                }
            });
           

            socket.Emit("getUtf8");
            ManualResetEvent.WaitOne();
            socket.Close();
            var j = 0;
            foreach (var obj in events)
            {
                var str = (string) obj;
                Assert.Equal(correct[j++], str);
            }
        }
        public void Json10000000CharsTest()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("json10000000chars");
            });

            socket.On("json10000000chars",
                (data) =>
                {
                    log.Info("EVENT_MESSAGE data=" + data);
                    events.Enqueue(data);
                    ManualResetEvent.Set();
                });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = (JObject)events.Dequeue();
            var str = (string)obj["data"];
            Assert.Equal(10000000, str.Length);
        }
        public void ShouldGetBinaryDataAsAnArraybuffer()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("doge", (data) =>
            {
                events.Enqueue(data);
                ManualResetEvent.Set();
            });

            socket.Emit("doge");

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();

            var binData = (byte[])events.Dequeue();
            var exptected = System.Text.Encoding.UTF8.GetBytes("asdfasdf");
            var i = 0;
            foreach (var b in exptected)
            {
                Assert.Equal(b, binData[i++]);
            }
        }
        public void Cookie()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();
            var uri = CreateUri();
            options.Cookies.Add("connect.sid","12345");
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("get_cookie");                
            });

            socket.On("got_cookie",
                (data) =>
                {
                    log.Info("EVENT_MESSAGE data=" + data);
                    events.Enqueue(data);
                    ManualResetEvent.Set();
                });

            ManualResetEvent.WaitOne();
            socket.Close();
            var cookie = (string)events.Dequeue();

            Assert.Equal("connect.sid=12345", cookie);
        }
Exemple #55
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            socket = IO.Socket("ws://gomoku-lajosveres.rhcloud.com:8000");
            bool firstConnect = true;
            object oldData = new object();
            while(true)
            {
                Thread.Sleep(100);
                socket.On("ChatMessage", (data) =>
                {
                    if(firstConnect || oldData != data)
                    {
                        firstConnect = false;
                        string chatSender;
                        string message = ((JObject)data)["message"].ToString();

                        if (((JObject)data)["from"] != null)
                        {
                            chatSender = ((JObject)data)["from"].ToString();
                        }
                        else
                        {
                            chatSender = "Server";
                        }
                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            ChatMessage chatMessage = new ChatMessage(chatSender, DateTime.Now.ToString("hh:mm:ss tt"), message);
                            chatBox.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                            chatBox.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                            chatBox.Items.Add(chatMessage);
                            if (((JObject)data)["message"].ToString() == "Welcome!")
                            {
                                
                              
                                socket.Emit("MyNameIs", txtYourName.Text);
                                socket.Emit("ConnectToOtherPlayer");
                            }
                            
                        }));
                        oldData = data;
                    }
                });
            }
        }
        public void MessageTestHebrew()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            var events = new Queue<object>();

            var options = CreateOptions();


            options.Transports = ImmutableList.Create<string>(Polling.NAME);

            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Emit("test", "csdataてすとבדיקה");
            });

            socket.On("hi",
                (data) =>
                {
                    log.Info("EVENT_MESSAGE");
                    events.Enqueue(data);
                    //socket.Emit("test", "2csdataてすとבדיקה");
                    ManualResetEvent.Set();
                });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            var obj = events.Dequeue();
            Assert.Equal("more data", obj);
        }
        public void ShouldSendBinaryDataAsAnArraybufferMixedWithJson()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag = false;

            var buf = System.Text.Encoding.UTF8.GetBytes("howdy");
            var jobj = new JObject();
            jobj.Add("hello", "lol");
            jobj.Add("message", buf);
            jobj.Add("goodbye", "gotcha");

            var options = CreateOptions();
            //options.Transports = ImmutableList.Create<string>(Polling.NAME);

            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("jsonbuff-ack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                log.Info("EVENT_DISCONNECT");
            });

            socket.Emit("jsonbuff", jobj);

            ManualResetEvent.WaitOne();
            Task.Delay(1).Wait();

            log.Info("About to wait 1sec");
            
            //Task.Delay(1000).Wait();
            log.Info("About to call close");
            socket.Close();
            //Task.Delay(1000).Wait();
            Assert.True(Flag);
            log.Info("Finish");
        }
        public void ShouldWorkWithAcks()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);


            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.Emit("ack");

            socket.On("ack", (cb) =>
            {
                var obj = new JObject();
                obj["b"] = true;
                var iack = (IAck) cb;
                iack.Call(5, obj);
            });

            socket.On("got it",
                (data) =>
                {
                    log.Info("got it");
                    ManualResetEvent.Set();
                });

            ManualResetEvent.WaitOne();
            socket.Close();

        }
        public async Task ShouldSendEventsWithArraybuffersInTheCorrectOrder()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag = false;
            var buf = System.Text.Encoding.UTF8.GetBytes("abuff1");

            var options = CreateOptions();
            var uri = CreateUri();
            socket = IO.Socket(uri, options);
            socket.On("abuff2-ack", () =>
            {
                Flag = true;
                ManualResetEvent.Set();
            });


            await Task.Delay(5000);
            socket.Emit("abuff1", buf);
            socket.Emit("abuff2", "please arrive second");
            ManualResetEvent.WaitOne();
            Assert.True(Flag);
        }
Exemple #60
0
        public void ListenData()
        {
            socket = IO.Socket(Settings.Default.IP_server);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Dispatcher.Invoke(() =>
                {
                    //   Lview.Items.Add("Connected");
                });
            });
            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                Dispatcher.Invoke(() =>
                {
                    Lview.Items.Add(((Newtonsoft.Json.Linq.JObject)data).ToString());
                });
            });
            socket.On(Socket.EVENT_CONNECT_ERROR, (data) =>
            {
                if (!isError)
                {
                    Dispatcher.Invoke(() =>
                    {
                        Lview.Items.Add("XẢY RA LỖI KẾT NỐI VỚI SERVER");
                    });
                    isError = true;
                }
            });

            socket.On(Socket.EVENT_ERROR, (data) =>
            {
                Dispatcher.Invoke(() =>
                {
                    Lview.Items.Add(((Newtonsoft.Json.Linq.JObject)data).ToString());
                });
            });

            #region Socket nhận ChatMessage
            socket.On("ChatMessage", (data) =>
            {
                string Message = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                string Msg = "";
                DateTime dt = DateTime.Now;
                #region Tin nhắn Welcome!
                if (Message == "Welcome!")
                {
                    Dispatcher.Invoke(() =>
                    {
                        TextBlock tblock = new TextBlock();
                        tblock.FontWeight = FontWeights.Bold;
                        Msg = "Server";
                        Msg += "\t\t\t\t" + dt.ToLongTimeString();
                        tblock.Text = Msg;
                        Lview.Items.Add(tblock);
                        Lview.Items.Add(Message);
                        Msg = "------------------------------------------------------";
                        Lview.Items.Add(Msg);
                        ClientName = txtName.Text.Trim();
                    });
                    
                    if(!ClientName.Equals("Guest"))
                    {
                        socket.Emit("MyNameIs", ClientName);
                    }
                    socket.Emit("ConnectToOtherPlayer");

                }
                #endregion

                #region Tin nhắn thông báo kết nối và thứ tự 2 người chơi
                else if (Message.Contains("<br />"))
                {
                    int index = Message.IndexOf("<br />");
                    string s1 = Message.Substring(0, index);
                    string s2 = Message.Substring(index + 6);
                    Dispatcher.Invoke(() =>
                    {
                        TextBlock tblock = new TextBlock();
                        tblock.FontWeight = FontWeights.Bold;
                        Msg = "Server";
                        Msg += "\t\t\t\t" + dt.ToLongTimeString();
                        tblock.Text = Msg;
                        Lview.Items.Add(tblock);
                        Lview.Items.Add(s1);
                        Lview.Items.Add(s2);
                        Msg = "------------------------------------------------------";
                        Lview.Items.Add(Msg);
                    });
                    // Nếu kiểu chơi là máy tự chơi online thì thực hiện kiểm tra thứ tự người chơi
                    // Nếu là người chơi thứ nhất thì cho máy tiến hành tự đánh trước vị trí giữa bàn cờ
                    if(Type == PlayingType.ComOnline)
                    {
                        if (s2 != "You are the second player!")
                        {
                            Board.ActivePlayer = CellPlayer.Player2;
                            Board.PlayAtOnline(Board.BOARD_SIZE / 2 + 1, Board.BOARD_SIZE / 2 + 1);
                            socket.Emit("MyStepIs", JObject.FromObject(new { row = Board.BOARD_SIZE / 2, col = Board.BOARD_SIZE / 2}));
                        }
                    }

                }
                #endregion

                #region Tin nhắn từ người chơi khác
                else if (((Newtonsoft.Json.Linq.JObject)data).Count > 1)
                {
                    Dispatcher.Invoke(() =>
                    {
                        TextBlock tblock = new TextBlock();
                        tblock.FontWeight = FontWeights.Bold;
                        Msg = ((Newtonsoft.Json.Linq.JObject)data)["from"].ToString();
                        Msg += "\t\t\t\t" + dt.ToLongTimeString();
                        tblock.Text = Msg;
                        Lview.Items.Add(tblock);
                        Lview.Items.Add(Message);
                        Msg = "------------------------------------------------------";
                        Lview.Items.Add(Msg);
                    });
                }
                #endregion

                #region Tin nhắn bình thường từ Server
                else
                {
                    Dispatcher.Invoke(() =>
                    {
                        TextBlock tblock = new TextBlock();
                        tblock.FontWeight = FontWeights.Bold;
                        Msg = "Server";
                        Msg += "\t\t\t\t" + dt.ToLongTimeString();
                        tblock.Text = Msg;
                        Lview.Items.Add(tblock);
                        Lview.Items.Add(Message);
                        Msg = "------------------------------------------------------";
                        Lview.Items.Add(Msg);
                    });
                }
                #endregion
            });
            #endregion

            #region Socket nhận thông báo kết thúc lượt chơi
            socket.On("EndGame", (data) =>
            {
                Dispatcher.Invoke(() =>
                {
                    string Msg;
                    TextBlock tblock = new TextBlock();
                    tblock.FontWeight = FontWeights.Bold;
                    Msg = "Server";
                    Msg += "\t\t\t\t" + DateTime.Now.ToLongTimeString();
                    tblock.Text = Msg;
                    Lview.Items.Add(tblock);
                    Msg = ((Newtonsoft.Json.Linq.JObject)data)["message"].ToString();
                    Lview.Items.Add(Msg);
                    Msg = "------------------------------------------------------";
                    Lview.Items.Add(Msg);
                    Dispatcher.Invoke(() =>
                    {
                        ugrid.Children.Clear();
                        VeBanCo();
                    });
                    if(Type == PlayingType.ComOnline)
                    {
                        Board.ResetBoard();
                        Board.isEndGame = true;
                        btnComOnline.Content = "New Game!";
                    }
                    else if(Type == PlayingType.POnline)
                    {
                        btnMain.Content = "New Game!";
                    }
                });
            });
            #endregion

            #region Socket nhận thông tin nước đi
            socket.On("NextStepIs", (data) =>
            {
                int player = int.Parse(((Newtonsoft.Json.Linq.JObject)data)["player"].ToString());
                int row = int.Parse(((Newtonsoft.Json.Linq.JObject)data)["row"].ToString());
                int col = int.Parse(((Newtonsoft.Json.Linq.JObject)data)["col"].ToString());
                CaroButton button = (CaroButton)this.Dispatcher.Invoke(new GetButtonDelegate(GetButton), row + 1, col + 1);
                // player = 0 là nước đi của người chơi
                if (player == 0)
                {
                    Dispatcher.Invoke(() =>
                    {
                        Ellipse ell = new Ellipse();
                        ell.Width = ell.Height = 25;
                        ell.Fill = Brushes.Black;
                        button.Content = ell;
                    });
                }
                // player = 1 là nước đi của đối thủ
                else
                {
                    Dispatcher.Invoke(() =>
                    {
                        Ellipse ell = new Ellipse();
                        ell.Width = ell.Height = 25;
                        RadialGradientBrush RadialBrush = new RadialGradientBrush();
                        RadialBrush.GradientOrigin = new Point(0.9, 0.9);
                        RadialBrush.GradientStops.Add(new GradientStop(Colors.Black, 0.0));
                        RadialBrush.GradientStops.Add(new GradientStop(Colors.White, 0.75));
                        ell.Stroke = Brushes.Black;
                        ell.Fill = RadialBrush;
                        button.Content = ell;
                    });
                    // Nếu người chơi là máy tự động chơi thì thực hiện tự động tìm nước đi để đánh
                    if(Type == PlayingType.ComOnline)
                    {
                        Board.ActivePlayer = CellPlayer.Player1;
                        Board.PlayAtOnline(row + 1, col + 1);
                        Thread Com = new Thread(Board.ComPlayOnline);
                        Com.IsBackground = true;
                        Com.Start();
                    }
                }
            });
            #endregion
        }