예제 #1
0
        /// <summary>
        /// Initializes the socket and sets-up all the events to listen to.
        /// Server certifaction validation is ingnored, because the server uses a self-signed certificate.
        /// </summary>
        /// <param name="adress"></param>
        public void Initialize(string adress, bool ignoreServerCertificateValidation) {
            _socket = IO.Socket(adress, new IO.Options() { Secure = true, IgnoreServerCertificateValidation = ignoreServerCertificateValidation });

            _socket.On("register-accepted", (data) => {
                Console.WriteLine("Succesfull connected with Server");
            });
            _socket.On("register-failed", (data) => {
                string errorMessage = data.ToString();
                Console.WriteLine("Failed to connected with Server: {0}", errorMessage);
            });
            _socket.On("message", (data) => {
                var message = JsonConvert.DeserializeObject<JsonReceivedMessage>(data.ToString());
                OnMessageReceived(this, new MessageReceivedEventArgs() { Identifier = message.Sender, Message = message.Message, TimeStamp = message.Timestamp, GroupHash = message.GroupHash });
            });
            _socket.On("user-search", (data) => {
                List<Client> clients = JsonConvert.DeserializeObject<List<Client>>(data.ToString());
                OnUserSearch(this, new UserSearchEventArgs() { FoundMembers = clients });
            });
            _socket.On("user-confirm", (data) => {
                var client = JsonConvert.DeserializeObject<Client>(data.ToString());
                OnUserConfirm(this, new UserConfirmEventArgs() { PublicKey = client.PublicKey, UserName = client.UserName });
            });
            _socket.On("joined-group", (data) => {
                var message = JsonConvert.DeserializeObject<JsonJoinedGroup>(data.ToString());
                OnGroupJoined(this, new GroupJoinedEventArgs() { GroupName = message.GroupName, GroupHash = message.GroupHash, Members = message.Members });
            });

            _socket.Connect();
        }
        public void Connect()
        {
            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.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                socket.Disconnect();
            });

            socket.On(Socket.EVENT_DISCONNECT,
                (data) =>
                {
                    log.Info("EVENT_DISCONNECT");
                    Message = (string) data;
                    ManualResetEvent.Set();
                });

            //socket.Open();
            ManualResetEvent.WaitOne();
            socket.Close();
            Assert.Equal("io client disconnect", this.Message);
        }
예제 #3
0
 public void AttachToSocket(Socket socket)
 {
     socket.On("Play", Play);
     socket.On("Pause", Pause);
     socket.On("Stop", Stop);
     socket.On("SetTrackId", (id) => SetTrackId((string) id));
 }
        public WebNfcListener(string ident)
        {
            if (!ident.Contains("@"))
                throw new ArgumentException("Invalid ident - missing @");
            var parts = ident.Split('@');
            if(parts.Length != 2)
                throw new ArgumentException("Invalid ident - invalid length");
            _endpoint = parts[0];
            _address = parts[1];

            _ioHandler = IO.Socket(_address);

            _ioHandler.On(Socket.EVENT_CONNECT, (obj) =>
            {
                OnConnected?.Invoke();
            });

            _ioHandler.On("scanner.registered", (obj) =>
            {
                var scanner = NfcScanner.FromJson(obj as string);
                OnRegistered?.Invoke(scanner);
            });
            _ioHandler.On("scanner.scanned", (obj) =>
            {
                var scanner = NfcScanner.FromJson(obj as string);

            });
        }
예제 #5
0
        private void initSocket(string server)
        {
            socket = IO.Socket(server);

            socket.On(Socket.EVENT_CONNECT, async () =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() =>
                {
                    viewModel.ServerStatus = "Connected";
                }).AsTask();
            });


            socket.On(Socket.EVENT_CONNECT_ERROR, async () =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    viewModel.ServerStatus = "Can't connect";
                }).AsTask();
            });

            socket.On(Socket.EVENT_DISCONNECT, async () =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    viewModel.ServerStatus = "Not connected";
                }).AsTask();
            });
        }
        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);
        }
        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);
        }
예제 #8
0
 public static void registerClient()
 {
     _socket = IO.Socket(HostURL);            
     if (MediateClass.UserVM.UserInfo != null)
     {
         _socket.Emit("storeMyID", MediateClass.UserVM.UserInfo.UserId);
     }
 }
        public SwitchClient(Uri serverUrl)
        {
            this.serverUrl = serverUrl;
            socket = IO.Socket(serverUrl);

            socket.On(Socket.EVENT_CONNECT, OnConnect);
            socket.On(SwitchEvent, OnSwitchEvent);
        }
예제 #10
0
        public ChatFragment(string username, Socket socket, AlertDialog alert)
        {
            this.username = username;
            this.socket = socket;
            this.adapter = new ChatAdapter(chatItems);

            AttachSocketEvents(alert);
        }
예제 #11
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 }));
        }
예제 #12
0
 public Client(View view)
 {
     stopWaitHandle = new AutoResetEvent(false);
     m_SavePath     = "";
     m_Files        = new Dictionary <int, string>();
     m_View         = view;
     // Fill in server IP.
     m_Socket = IO.Socket("");
 }
예제 #13
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 }));
 }
예제 #14
0
    // Use this for initialization
    void Start()
    {
        socket = IO.Socket(server);

        socket.On("connect", () =>
        {
            Debug.Log("Connected to Larynx.");
        });
    }
예제 #15
0
 private void btn_newgame_Click(object sender, RoutedEventArgs e)
 {
     type   = 3;
     socket = IO.Socket("ws://gomoku-lajosveres.rhcloud.com:8000");
     Connect.KetNoi(socket, txt_name.Text);
     drawBoard();
     ban_co.IsEnabled = true;
     PlayerWin        = 0;
 }
예제 #16
0
        /// <summary>
        /// Disconnect from Octoblu
        /// </summary>
        public void Disconnect()
        {
            Trace.WriteLine("OctobluClient: Disconnecting from Octoblu");

            // Disconnect from Octoblu and end this process
            //_socket.Disconnect();
            _socket.Close();
            _socket = null;
            _endEvent.Set();
        }
예제 #17
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());
            }
        }
예제 #18
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));
        }
예제 #19
0
        private void SetupMeshbluConnection()
        {
            var opts = new IO.Options();

            opts.Port     = _config.MeshbluPort;
            opts.ForceNew = true;
            opts.Secure   = true;
            opts.IgnoreServerCertificateValidation = true;

            _socket = Quobject.SocketIoClientDotNet.Client.IO.Socket(_config.MeshbluUrl, opts);
        }
        public void Connect()
        {
            socket = IO.Socket("http://localhost:3000");
            socket.On(Sock.EVENT_CONNECT, () =>
            {
            });

            socket.On(Sock.EVENT_DISCONNECT, (data) =>
            {
                Message = (string)data;
            });
        }
예제 #21
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";
            });
        }
 private void socketIOConnect()
 {
     if (socket == null)
     {
         socket = IO.Socket(ip);
         socketIOManager();
     }
     else
     {
         updateStatus("Connected");
     }
 }
예제 #23
0
        public Form1()
        {
            InitializeComponent();
            socket = IO.Socket("http://127.0.0.1:3000");
            socket.On(Socket.EVENT_CONNECT, () => {
                Console.WriteLine("connected");
            });

            socket.On("unique", (data) => {
                this.SetText((String)data);
            });
        }
예제 #24
0
        public void ShouldFireReconnectEventsOnSocket()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag             = false;
            var reconnects = 0;
            var events     = new Queue <int>();

            var correct = new int[]
            {
                1, 2, 2
            };

            var options = CreateOptions();

            options.Reconnection         = true;
            options.Timeout              = 0;
            options.ReconnectionAttempts = 2;
            options.ReconnectionDelay    = 10;
            var uri = CreateUri();

            var manager = new Manager(new Uri(uri), options);

            socket = manager.Socket("/timeout_socket");

            socket.On(Socket.EVENT_RECONNECT_ATTEMPT, (attempts) =>
            {
                log.Info("EVENT_RECONNECT_ATTEMPT");
                reconnects++;
                events.Enqueue(int.Parse((attempts).ToString()));
            });

            socket.On(Socket.EVENT_RECONNECT_FAILED, () =>
            {
                log.Info("EVENT_RECONNECT_FAILED");
                Flag = true;
                events.Enqueue(reconnects);
                socket.Close();
                manager.Close();
                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            var j = 0;

            foreach (var number in events)
            {
                Assert.Equal(correct[j++], number);
            }
        }
예제 #25
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);
            }
        }
예제 #26
0
        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());
                });
            }
        }
예제 #27
0
 private void GameInit()
 {
     PlayPanel.Children.Clear();
     CreatePlayGround();
     ChatTb.Focus();
     MyName = NameTb.Text;
     if (Board.CurrentMode == PlayMode.Online || Board.CurrentMode == PlayMode.MachineVsOnline)
     {
         GomokuSocket = IO.Socket(WebConfigurationManager.AppSettings.Get("ServerAddress"));
         InitConnect(); //Initialize Connect
         ChatConnect(); //Create Thread for chatting
         GamePlayConnect(); //Create Threads for playing
     }
 }
예제 #28
0
 public static void Connect(string imHost, string imToken, string uid)
 {
     _socket = SocketIO.IO.Socket(imHost, new SocketIO.IO.Options
     {
         Transports = Quobject.Collections.Immutable.ImmutableList.Create <string>().Add("websocket"),
         Query      = new Dictionary <string, string>
         {
             { "token", imToken },
             { "uid", uid },
             { "client", "Windows 10" },
         }
     });
     _socket.On("message", obj => OnMessageReceived?.Invoke(obj as JObject));
 }
예제 #29
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());
            });
        }
예제 #30
0
        public void ShouldNotConnectWhenAutoconnectOptionSetToFalse()
        {
            var log = LogManager.GetLogger(Global.CallerName());

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

            var options = CreateOptions();

            options.AutoConnect = false;
            var uri = CreateUri();

            socket = IO.Socket(uri, options);
            Assert.Null(socket.Io().EngineSocket);
        }
예제 #31
0
 void Connect()
 {
     if (socket == null)
     {
         socket = IO.Socket(server);
         socket.On(Socket.EVENT_CONNECT, () =>
         {
             Debug.Log("[Socket] Connected");
         });
         socket.On("move", (data) =>
         {
             MoveCommand moveCommand = JsonConvert.DeserializeObject <MoveCommand>(data.ToString());
             HandleCommand(moveCommand);
         });
     }
 }
예제 #32
0
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            //socket = IO.Socket("http://localhost:3000");
            socket = IO.Socket("http://192.168.12.120:3000");
            socket.On("EntityAdded", (data) =>
            {
                clientId = data.ToString();
                _dispatcher.BeginInvoke(DispatcherPriority.Normal, new AddEntityDelegate(AddEntity));
            });


            socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT, () =>
            {
                StatusLable.Dispatcher.Invoke(new Action(() => { StatusLable.Content = "Connected"; StatusLable.Foreground = Brushes.Green; }));
            });
        }
예제 #33
0
파일: LinkIOImp.cs 프로젝트: aragoubi/Nine
        public LinkIO connect(Action listener)
        {
            IO.Options opts = new IO.Options();
            Dictionary<String, String> query = new Dictionary<String, String>();
            query.Add("user", user);

            if(id != "")
                query.Add("id", id);

            opts.Query = query;
            opts.AutoConnect = false;

            socket = IO.Socket("http://" + serverIP, opts);

            socket.On("users", (e) =>
            {
                if (userInRoomChangedListener != null)
                    userInRoomChangedListener.Invoke(((JArray) e).ToObject<List<User>>());
            });

            socket.On(Socket.EVENT_CONNECT, () =>
            {
                connected = true;
                listener.Invoke();
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                connected = false;
            });

            socket.On("event", (Object o) =>
            {
                JObject evt = (JObject) o;
                String eventName = (String) evt.SelectToken("type");
                if (eventListeners.ContainsKey(eventName))
                {
                    eventListeners[eventName].Invoke(new Event(evt));
                }                        


            });

            socket.Connect();

            return this;
        }
예제 #34
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 override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            bSend.TouchUpInside += (object sender, EventArgs e) => {
                var message = tfMessage.Text;
                socket.Emit("message", message);
            };

            socket = IO.Socket(Constants.HOST);
            socket.On ("message", (message) => {
                InvokeOnMainThread(() => {
                    var alert = new UIAlertView("From server:", message.ToString(), null, "OK", null);
                    alert.Show();
                });
            });
        }
        public WebNfcListener(string ident)
        {
            if (!ident.Contains("@"))
                throw new ArgumentException("Invalid ident - missing @");
            var parts = ident.Split('@');
            if(parts.Length != 2)
                throw new ArgumentException("Invalid ident - invalid length");
            _endpoint = parts[0];
            _address = parts[1];

            _ioHandler = IO.Socket($"http://{_address}", new IO.Options {AutoConnect = false, Reconnection = true});

            _ioHandler.On(Socket.EVENT_CONNECT, (obj) =>
            {
                OnConnected?.Invoke();
            });

            _ioHandler.On("scanner.registered", (obj) =>
            {
                var scanner = NfcScanner.FromObject(obj);
                if (!Scanners.Exists(x => x.DeviceId == scanner.DeviceId))
                {
                    Scanners.Add(scanner);
                    OnScannerRegistered?.Invoke(scanner);
                }
            });
            _ioHandler.On("scanner.disconnected", (obj) =>
            {
                dynamic o = obj;
                string deviceId = o.device_id;
                var scanner = Scanners.FirstOrDefault(x => x.DeviceId == deviceId);
                if (scanner != null)
                    Scanners.Remove(scanner);
                OnScannerDisconnected?.Invoke(scanner);
            });
            _ioHandler.On("scanner.scanned", (obj) =>
            {
                dynamic o = obj;
                string deviceId = o.device_id;
                var scanner = Scanners.FirstOrDefault(x => x.DeviceId == deviceId);

                var s = new NfcScan {Scanner = scanner, CardId = ((dynamic)obj).card_id };
                OnScanned?.Invoke(s);

            });
        }
예제 #37
0
        private void btn_machine_online_Click(object sender, RoutedEventArgs e)
        {
            type             = 4;
            ban_co.IsEnabled = true;
            for (int x = 0; x < n; x++)
            {
                for (int y = 0; y < n; y++)
                {
                    caro[x, y] = 0;
                }
            }
            drawBoard();
            PlayerWin = 0;
            string connect = ConfigurationManager.ConnectionStrings["LINK_GOMOKU"].ConnectionString;

            socket = IO.Socket(connect);
            Connect.KetNoi(socket, txt_name.Text);
        }
예제 #38
0
        public Boolean connectSocketServer(String host)
        {
            Boolean done = false;

            if (host != "")
            {
                try
                {
                    socketServer = IO.Socket(host);
                    done         = true;

                    socketServer.On("gameInfo", (infoPartida) =>
                    {
                        _returnedFromServer = infoPartida.ToString();
                        Console.WriteLine("gameInfo");
                        gameInfo(_returnedFromServer, EventArgs.Empty);
                    });

                    socketServer.On("neighborChange", (data) =>
                    {
                        _returnedFromServer = data.ToString();
                        Console.WriteLine("neighborChange");
                        neighborChange(_returnedFromServer, EventArgs.Empty);
                    });

                    socketServer.On("positionConfirmed", (data) =>
                    {
                        _returnedFromServer = data.ToString();
                        Console.WriteLine("positionConfirmed");
                        positionConfirmed(_returnedFromServer, EventArgs.Empty);
                    });
                }
                catch (Exception e)
                {
                    ClErrors.reportError(e.Message);
                }
            }
            else
            {
                ClErrors.reportError("Can't connect socket is empty!");
            }

            return(done);
        }
예제 #39
0
        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);
        }
예제 #40
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button> (Resource.Id.bSend);
            EditText edit = FindViewById<EditText> (Resource.Id.etMessage);

            button.Click += delegate {
                var message = edit.Text;
                socket.Emit("message", message);
            };

            socket = IO.Socket(Constants.HOST);
            socket.On ("message", delegate(object obj) {
                RunOnUiThread(() => {
                    var message = obj.ToString ();
                    var alert = Toast.MakeText (this, message, ToastLength.Short);
                    alert.Show ();
                });
            });
        }
예제 #41
0
        public SocketService(string server, string userToken = "5601ab2d299cfb5a7698566158fcb2bc350701b9ac77b6f72e52c260fab0da57") : this(server)
        {
            UserToken        = userToken;
            EventsDictionary = new ConcurrentDictionary <string, object>();
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ValidateCert;
            var options = new IO.Options()
            {
                AutoConnect = true,
                //ExtraHeaders = new Dictionary<string, string>() { { authToken, UserToken } },
                Reconnection      = true,
                ReconnectionDelay = 10,
            };
            options.Transports = ImmutableList.Create <string>(Polling.NAME);

            socket = IO.Socket(server, options);
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                socket.Emit($"/v1/login/{UserToken}");
            });
            socket.On(Socket.EVENT_DISCONNECT, () =>
                      Debug.WriteLine("Disconnecting")
                      );
            socket.On(
                Socket.EVENT_ERROR, ErrorLog);
            socket.On("hi", (data) =>
            {
                Debug.WriteLine(data);
                socket.Disconnect();
            });

            socket.On(Socket.EVENT_MESSAGE, (data) =>
            {
                Debug.WriteLine("Message recieved");
            });
            socket.On(Socket.EVENT_CONNECT_ERROR, ErrorLog);
            socket.On(Socket.EVENT_RECONNECT_ATTEMPT, () => Debug.WriteLine("Attempting reconnect"));
            socket.On(Socket.EVENT_RECONNECT_ERROR, ErrorLog);
            socket.On(Socket.EVENT_RECONNECT_FAILED, () => Debug.WriteLine("Reconnect failed"));
        }
예제 #42
0
        static void Main(string[] args)
        {
            port.BaudRate = 9600;
            var ser = Console.ReadLine().Trim();

            connect();
            Console.WriteLine("Connected on port : " + port.PortName);
            aTimer          = new System.Timers.Timer();
            aTimer.Interval = 1500;

            socket = IO.Socket(ser);

            socket.On("NTC", (data) =>
            {
                if (data.ToString() != l)
                {
                    l = data.ToString();
                    port.WriteLine(data.ToString());;
                }
                Console.WriteLine(data.ToString());
            });
        }
예제 #43
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();
            });
        }
예제 #44
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;

            //    }

            //});
            
            
        }
예제 #45
0
        public void ShouldNotTryToReconnectAndShouldFormAConnectionWhenConnectingToCorrectPortWithDefaultTimeout()
        {
            var log = LogManager.GetLogger(Global.CallerName());

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


            var options = CreateOptions();

            options.Reconnection      = true;
            options.ReconnectionDelay = 10;
            var uri = CreateUri();

            var manager = new Manager(new Uri(uri), options);

            socket = manager.Socket("/valid");

            manager.On(Manager.EVENT_RECONNECT_ATTEMPT, () =>
            {
                Flag = true;
            });

            socket.On(Socket.EVENT_CONNECT, async() =>
            {
                // set a timeout to let reconnection possibly fire
                log.Info("EVENT_CONNECT");
                await Task.Delay(1000);

                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            log.Info("after WaitOne");
            socket.Close();
            manager.Close();
            Assert.False(Flag);
        }
예제 #46
0
        public void ShouldFireErrorOnSocket()
        {
            var log = LogManager.GetLogger(Global.CallerName());

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

            var options = CreateOptions();

            options.Reconnection = true;
            var uri = CreateUri();

            var manager = new Manager(new Uri(uri), options);

            socket = manager.Socket("/timeout_socket");

            socket.On(Socket.EVENT_ERROR, (e) =>
            {
                var exception = (EngineIOException)e;
                log.Info("EVENT_ERROR");
                events.Enqueue(exception.code);
                socket.Close();
                manager.Close();
                ManualResetEvent.Set();
            });

            socket.On(Socket.EVENT_CONNECT, () =>
            {
                log.Info("EVENT_CONNECT");
                manager.EngineSocket.OnPacket(new Packet(Packet.ERROR, "test"));
            });

            ManualResetEvent.WaitOne();
            var obj = (string)events.Dequeue();

            Assert.Equal("test", obj);
        }
예제 #47
0
        public void ShouldTryToReconnectTwiceAndFailWhenRequestedTwoAttemptsWithIncorrectAddressAndReconnectEnabled()
        {
            var log = LogManager.GetLogger(Global.CallerName());

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

            var options = CreateOptions();

            options.Reconnection         = true;
            options.ReconnectionAttempts = 2;
            options.ReconnectionDelay    = 10;
            var uri = "http://localhost:3940";


            var manager = new Manager(new Uri(uri), options);

            socket = manager.Socket("/asd");

            manager.On(Manager.EVENT_RECONNECT_ATTEMPT, () =>
            {
                log.Info("EVENT_RECONNECT_ATTEMPT");
                reconnects++;
            });

            manager.On(Manager.EVENT_RECONNECT_FAILED, () =>
            {
                log.Info("EVENT_RECONNECT_FAILED");
                Flag = true;
                socket.Disconnect();
                manager.Close();
                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            Assert.Equal(2, reconnects);
        }
예제 #48
0
        public void connectInternet()
        {
            mSocket = IO.Socket(this.LocalHost);
            if (this.checkConnect == false)
            {
                this.checkConnect = true;
                mSocket.Connect();
            }

            mSocket.On(Socket.EVENT_CONNECT, () =>
            {
                BeginInvoke((Action)(() =>
                {
                    Debug.WriteLine("OK");
                    this.tb_StatusConnection.Text = "Kết nối thành công Internet.!";
                }), null);
            });

            mSocket.On(Socket.EVENT_DISCONNECT, () =>
            {
                BeginInvoke((Action)(() =>
                {
                    this.tb_StatusConnection.Text = "Ngắt kết nối.!";
                }), null);
            });

            mSocket.On("Doc danh sach phong choi", (data) =>
            {
                BeginInvoke((Action)(() =>
                {
                    string[] danhsachphong = data.ToString().Split('|');
                    this.lb_DanhSachPhong.Items.Clear();
                    foreach (var phong in danhsachphong)
                        if (!String.IsNullOrWhiteSpace(phong))
                            this.lb_DanhSachPhong.Items.Add(phong);
                }), null);
            });
        }
예제 #49
0
        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);
        }
예제 #50
0
        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 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);
        }
예제 #52
0
        private void SetupMeshbluConnection()
        {
            var opts = new IO.Options();

            opts.Port = _config.MeshbluPort;
            opts.ForceNew = true;
            opts.Secure = true;
            opts.IgnoreServerCertificateValidation = true;

            _socket = Quobject.SocketIoClientDotNet.Client.IO.Socket(_config.MeshbluUrl, opts);
        }
예제 #53
0
        private void btndisconnect_Click(object sender, RoutedEventArgs e)
        {
            if (socket != null)
            {
                socket.Disconnect();
                btnconnect.IsEnabled = false;
                btndisconnect.IsEnabled = false;
                btnusername.IsEnabled = false;
                btnnewgame.IsEnabled = false;
                btnchatbox.IsEnabled = false;
                m3.IsChecked = false;
                m4.IsChecked = false;

                Board.PropertyMode = -1;

                setDefaultParameter();
             
                socket = null;
            }
        }
        public void ShouldNotTryToReconnectWithIncorrectPortWhenReconnectionDisabled()
        {
            var log = LogManager.GetLogger(Global.CallerName());
            log.Info("Start");
            ManualResetEvent = new ManualResetEvent(false);
            Flag = false;


            var options = CreateOptions();
            options.Reconnection = false;
            var uri = "http://localhost:3940";

            var manager = new Manager(new Uri(uri), options);
            socket = manager.Socket("/invalid");

            manager.On(Manager.EVENT_RECONNECT_ATTEMPT, () =>
            {
                Flag = true;
            });

            manager.On(Manager.EVENT_CONNECT_ERROR, async () =>
            {
                // set a timeout to let reconnection possibly fire
                log.Info("EVENT_CONNECT_ERROR");
                await Task.Delay(1000);
                ManualResetEvent.Set();
            });

            ManualResetEvent.WaitOne();
            log.Info("after WaitOne");
            socket.Disconnect();
            manager.Close();
            Assert.False(Flag);     
        }
예제 #55
0
        /// <summary>
        /// Disconnect from Octoblu
        /// </summary>
        public void Disconnect()
        {
            Trace.WriteLine("OctobluClient: Disconnecting from Octoblu");

            // Disconnect from Octoblu and end this process
            //_socket.Disconnect();
            _socket.Close();
            _socket = null;
            _endEvent.Set();
        }
예제 #56
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;
                    }
                });
            }
        }
예제 #57
0
파일: Api.cs 프로젝트: TNOCS/csTouch
        public void InitSocketConnection()
        {
            socket = Quobject.SocketIoClientDotNet.Client.IO.Socket(server);

            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Console.WriteLine("connected");
                //socket.Emit("hi");

                

            });
            socket.On("msg", o =>
            {
                Console.WriteLine(o.ToString());
            });

            

        }
예제 #58
0
 public AckImp(Socket socket, int id)
 {                
     this.socket = socket;
     this.Id = id;
 }
        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);
        }
        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++]);
            }
        }