Class to emulate socket.io javascript client capabilities for .net classes
Connection for wss or https urls
Inheritance: IDisposable, SocketIOClient.IClient
        void direct_Example()
        {
            var directSocket = new Client("http://127.0.0.1:3000/logger"); // url to the nodejs
            directSocket.Connect();
            directSocket.On("connect", (fn) =>
            {
                Console.WriteLine("\r\nConnected event...\r\n");
            });

            directSocket.On("traceEvent", (eventLog) =>
                {
                    // do something with eventLog
                });

            directSocket.Emit("messageAck", new { hello = "papa" });
        }
        public void createConnect()
        {
            //socketIO = new Client("http://168.63.151.29:3000");

            socketIO = new Client("http://test.twtstudio.com:3000/");
            socketIO.Message += socketIO_Message;
            socketIO.SocketConnectionClosed += socketIO_SocketConnectionClosed;
            socketIO.Error += socketIO_Error;

            socketIO.On("connect", (message) =>
            {
                Debug.WriteLine("on connect called!!!");
                JObject jo = new JObject();
                jo["username"] = "******";
                socketIO.Emit("join", jo);
            });


            socketIO.On("chat", async (message) =>
            {
                Debug.WriteLine("start listening");
                Debug.WriteLine(message.Json.ToJsonString());
                await SampleDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    JObject o = (JObject)JsonConvert.DeserializeObject(message.Json.ToJsonString());
                    JArray jb = (JArray)JsonConvert.DeserializeObject(o["args"].ToString());
                    JObject ob = (JObject)jb[0];

                    if (ob["roomNum"].ToString().Equals(Self.roomNum.ToString()))
                        ChangedEventHandler(ob["username"]+":"+ob["chat"]);
                });
            });

            socketIO.ConnectAsync();
        }
        public void Connect(HTransportOptions options)
        {
            this.connStatus = ConnectionStatus.CONNECTING;
            this.options = options;

            //TODO init the connection timeout value!!
            connTimeout = new TimeSpan(0, 0, 0, 0, options.Timeout);

            string endpointHost = options.EndpointHost;
            int endpointPort = options.EndpointPort;
            string endpointPath = options.EndpointPath;

            string endpointAdress = ToEndpointAdress(endpointHost, endpointPort, endpointPath);

            connTimeoutTimer = ThreadPoolTimer.CreateTimer(timeout_Elapsed, connTimeout);

            socketIO = new Client(endpointAdress);

            socketIO.Message += socketIO_Message;
            socketIO.SocketConnectionClosed += socketIO_SocketConnectionClosed;
            socketIO.Error += socketIO_Error;
            socketIO.On("connect", (message) =>
                {
                    if (this.options.AuthCb != null)
                        this.options.AuthCb(options.Login, Login);
                    else
                        Login(options.Login, options.Password);
                });
            socketIO.ConnectAsync();
        }
Exemple #4
0
    public void initialize()
    {
        socket = new SocketIOClient.Client("http://" + ip + "");

        socket.On("connect", (fn) => {
            Debug.Log("connect - socket");

            //Dictionary<string, string> args = new Dictionary<string, string>();
            //List<string> args = new List<string>();
            //args.Add("what's up?");
            //socket.Emit("SEND", args);
            //string valueout;
            //args.TryGetValue("msg", out valueout);
        });

        socket.On("keyPressed", (fn) => {
            string data = (string)fn.Json.args[0];

            string[] dataArray = data.Split(',');
            int millis         = int.Parse(dataArray[1]);

            int score = int.Parse(dataArray[2]);

            if (dataArray[0].Equals("0"))
            {
                manager.reciveLeft(millis, score);
            }
            if (dataArray[0].Equals("1"))
            {
                manager.reciveDown(millis, score);
            }
            if (dataArray[0].Equals("2"))
            {
                manager.reciveUp(millis, score);
            }
            if (dataArray[0].Equals("3"))
            {
                manager.reciveRight(millis, score);
            }
        });

        socket.On("startGame", (fn) => {
            Debug.Log("Gloworbo");
            gameFlowManagerScript.runOnline();
        });

        socket.Error += (sender, e) => {
            Debug.Log("Error " + e.Message.ToString());
            error = true;
        };

        socket.On("playerLeft", (fn) => {
            Application.LoadLevel(Application.loadedLevel);
        });

        if (!error)
        {
            socket.Connect();
        }
    }
Exemple #5
0
        private void connect()
        {
            websocket = new Client(HOST_URL);

            /* サーバとの接続が確定 */
            websocket.On("connect", (fn) =>
            {
                NotifyUpdateState(INROOM);
                Console.WriteLine("connect");
            });

            /* サーバからのプッシュ通知(誰かの状態が更新された)*/
            websocket.On("s2c_update_state", (data) =>
            {
                string json = "" + data.Json.Args[0];
                Console.WriteLine("update state : =" + json);
            });

            /* サーバからのプッシュ通知(新しくメンバーが追加) */
            websocket.On("s2c_message_register_member", (data) =>
            {
                string json = "" + data.Json.Args[0];
                Console.WriteLine("register new member :" + json);
            });

            websocket.Connect();
        }
Exemple #6
0
        public void Execute()
        {
            Console.WriteLine("Starting TestSocketIOClient Example...");

            socket = new Client("http://127.0.0.1:8000/"); // url to nodejs server

            socket.SocketConnectionClosed += SocketConnectionClosed;
            socket.Error += SocketError;

            // register for 'connect' event with io server
            socket.On("connect", (fn) =>
            {
                Console.WriteLine("\r\nConnected event...\r\n");
            });

            // received new message from the server
            socket.On("new", (data) =>
            {
                // json returned is in a wieird format ex: {"name":"new","args":[{"name":"sung","msg":"wefwef"}]} grab the right string from that (second part is what we're interested in)
                string jsonstr = data.Json.Args[0].ToString();

                // convert json string to message object
                Message msg = JsonConvert.DeserializeObject<Message>(jsonstr);

                // start a new thread to safely append the textbox text
                this.txtUpdateThread = new Thread(() => this.SetText(msg.name + ": " + msg.msg + "\r\n"));
                this.txtUpdateThread.Start();

            });

            // make the socket.io connection
            socket.Connect();
        }
        private void WorkerFunc()
        {
            try
            {
                var client = new RestClient(Host.Url, Session.Cookies);
                var res = client.Get("push_settings.json?ctype=mobile");
                var queryString = client.Content.SelectToken("query_string").Value<string>();

                var url = string.Format(@"https://notification-service-{0}{1}", Host.Uri.Host, queryString);

                _socket = new SocketIOClient.Client(url);

                _socket.Message += socket_MessageReceived;
                _socket.Error += socket_Error;
                _socket.Opened += socket_Opened;
                _socket.Connect();

            }
            catch (OperationCanceledException)
            {
                IsStarted = false;
            }
            catch (Exception ex)
            {
                IsStarted = false;
                Logger.LogError(ex);
                throw;
            }

        }
    void Start()
    {
        Debug.Log("Attempting to connect to server...");
        System.Net.WebRequest.DefaultWebProxy = null;

        string url = "http://45.56.101.79:80/";

        Debug.Log("Server url: " + url);

        socket = new SocketIOClient.Client(url);

        socket.On("connect", (fn) =>
        {
            Debug.Log("connect - socket");
            Dictionary <string, string> args = new Dictionary <string, string>();
            args.Add("msg", "what's up?");
            socket.Emit("SEND", args);
        });

        socket.On("RECV", (data) =>
        {
            Debug.Log(data.Json.ToJsonString());
        });

        socket.Error += (sender, e) =>
        {
            Debug.Log("socket Error: " + e.Message.ToString());
        };

        socket.Connect();
    }
 public SocketEventClient(string id, string url)
 {
     this.ClientId = id;
     this.State = ClientState.Disconnected;
     this.socket = new Client(url);
     this.socket.Connect();
     this.State = ClientState.Connected;
 }
Exemple #10
0
//start socket
    private void Start()
    {
        //get the sample player

        trans = GameObject.Find("SamplePlayer").GetComponent <Transform> ();


        socket = new SocketIOClient.Client("http://localhost:3000/");          //("http://localhost:3000");//


        socket.On("connect", (fn) => {
            //Debug.Log ("connect - socket");

            //Dictionary<string, string> args = new Dictionary<string, string>();


            //args.Add("zcock", "0");
            //args.Add("xcock", "0");

            //socket.Emit("send message", args);

            //socket.Emit("send message", "yo new socket in town");
        });

        socket.On("allppl", (data) => {
            Debug.Log("cockfucker" + data.Json.ToJsonString());

            //string jot =  JSONObject.Parse(data).ToString();
        });

        socket.On("new pos", (data) => {
            fuckdata        = JSONObject.Parse(data.Json.ToJsonString());
            JSONArray awesa = fuckdata.GetArray("args");
            positionData    = awesa.ToString();         //(string) data.Json.ToJsonString();

            usernamesocket = awesa[0].ToString();

            try{
                if (awesa[1].Obj.GetString("xcock") != null && awesa[1].Obj.GetString("zcock") != null)
                {
                    xman = awesa[1].Obj.GetString("xcock");
                    zman = awesa[1].Obj.GetString("zcock");
                }
            }catch {
            }
        });


        socket.On("new message", (data) => {
            //	Debug.Log ("fukeroo"+ data.ToString());

            fuckdata = JSONObject.Parse(data.Json.ToJsonString());
        });
        socket.Error += (sender, e) => {
            //Debug.Log ("socket Error: " + e.Message.ToString ());
        };
        socket.Connect();
    }            //end
        public PomeloClient(string url)
        {
            string checkedUrl = this.checkUrl(url);

            try{
                this.socket = new Client(checkedUrl);
            } catch (Exception e) {
                Console.WriteLine(string.Format("Error in new SocketIO:{0}", e.Message));
            }

            this.eventManager = new EventManager();
        }
Exemple #12
0
        public void InitializeSocket()
        {
            if(_client != null)
                _client.Close();
            _client = new Client(@"https://feed.bitfloor.com");
            _client.Message += SocketClientMessage;
            _client.Error += SocketClientError;
            _client.SocketConnectionClosed += SocketClientConnectionClosed;

            _client.On("order_new", (details) => { });
            _client.Connect("/1");
        }
Exemple #13
0
        public MtGoxWebSocketClient()
        {
            _client = new Client(MTGOXSOCKETURL);
            _client.Error += _client_Error;
            _client.Message += _client_Message;
            _client.SocketConnectionClosed += _client_SocketConnectionClosed;

            _client.On("subscribe", data => SetStatus("Subscribed to channel: " + data.Json.ToJsonString() + Environment.NewLine));
            _client.On("channel", data => SetStatus("Ticker: " + data.Json.ToJsonString() + Environment.NewLine));
            _client.On("connect", data => SetStatus("Connected to the socket.." + Environment.NewLine));

            _client.Connect("/mtgox");
        }
Exemple #14
0
    // https://github.com/kaistseo/UnitySocketIO-WebSocketSharp
    void Start()
    {
        socket = new SocketIOClient.Client("http://literature.uncontext.com:80/");

        socket.On("0", (data) => {
            Debug.Log (data.Json.ToJsonString());
        });
        socket.Error += (sender, e) => {
            Debug.Log ("socket Error: " + e.Message.ToString ());
        };

        socket.Connect();
    }
    // Use this for initialization
    void OnEnable()
    {
        client = new SocketIOClient.Client(serverAdress + "/?transport=polling");



        client.Opened  += SocketOpened;
        client.Message += SocketMessage;
        client.Error   += SocketError;
        client.SocketConnectionClosed += SocketConnectionClosed;

        client.Connect();
    }
Exemple #16
0
    // https://github.com/kaistseo/UnitySocketIO-WebSocketSharp

    void Start()
    {
        socket = new SocketIOClient.Client("http://literature.uncontext.com:80/");

        socket.On("0", (data) => {
            Debug.Log(data.Json.ToJsonString());
        });
        socket.Error += (sender, e) => {
            Debug.Log("socket Error: " + e.Message.ToString());
        };

        socket.Connect();
    }
Exemple #17
0
        //Awake is always called before any Start functions
        void Awake()
        {
            Debug.Log("start");
            sended = 0;
            // socket = new SocketIOClient.Client ("http://127.0.0.1:3000/");
            socket = new SocketIOClient.Client("https://unity-server.herokuapp.com/");

            socket.On("connect", (fn) => {
                Debug.Log("connect - socket");

                Dictionary <string, string> args = new Dictionary <string, string>();
                args.Add("scene", "game_start");
                socket.Emit("emit", args);
            });

            //socket.Send("nuwaaa");


            socket.On("message:receive", (data) => {
                Debug.Log(data.Json.ToJsonString());
                //text = data.Json.ToJsonString() + "\n" + text;
            });

            socket.Connect();

            //Check if instance already exists
            if (instance == null)
            {
                //if not, set instance to this
                instance = this;
            }

            //If instance already exists and it's not this:
            else if (instance != this)
            {
                //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
                Destroy(gameObject);
            }

            //Sets this to not be destroyed when reloading scene
            DontDestroyOnLoad(gameObject);

            //Assign enemies to a new List of Enemy objects.
            enemies = new List <Enemy>();

            //Get a component reference to the attached BoardManager script
            boardScript = GetComponent <BoardManager>();

            //Call the InitGame function to initialize the first level
            InitGame();
        }
    void Start()
    {
        socket = new SocketIOClient.Client("http://127.0.0.1:80/");
        socket.On("connect", (fn) => {
            Debug.Log ("connect - socket");

            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("msg", "what's up?");
            socket.Emit("SEND", args);
        });
        socket.On("RECV", (data) => {
            Debug.Log (data.Json.ToJsonString());
        });
        socket.Connect();
    }
		public void Execute()
		{
			Console.WriteLine("Starting TestSocketIOClient Example...");

			socket = new Client("http://127.0.0.1:3000/"); // url to the nodejs / socket.io instance

			socket.Opened += SocketOpened;
			socket.Message += SocketMessage;
			socket.SocketConnectionClosed += SocketConnectionClosed;
			socket.Error += SocketError;
			
			socket.HandShake.Headers.Add("OrganizationId", "1034");
			socket.HandShake.Headers.Add("UserId", "TestSample");

			// register for 'connect' event with io server
			socket.On("connect", (fn) =>
			{
				Console.WriteLine("\r\nConnected event...\r\n");
				Console.WriteLine("Emit Part object");

				// emit Json Serializable object, anonymous types, or strings
				//Part newPart = new Part() { X = 1, Y = 2, Z = 3 };
                //socket.Emit("JSONSkeleton", newPart);

			    JSONSkeleton newPart = new JSONSkeleton();
                socket.Emit("partInfo", newPart.ToJsonString());

			});

			
			// register for 'update' events - message is a json 'Part' object
			socket.On("update", (data) =>
			{
				Console.WriteLine("recv [socket].[update] event");
				//Console.WriteLine("  raw message:      {0}", data.RawMessage);
				//Console.WriteLine("  string message:   {0}", data.MessageText);
				//Console.WriteLine("  json data string: {0}", data.Json.ToJsonString());
				//Console.WriteLine("  json raw:         {0}", data.Json.Args[0]);

				// cast message as Part - use type cast helper
				Part part = data.Json.GetFirstArgAs<Part>();
				//Console.WriteLine(" Part Level:   {0}\r\n", part.Level);

			});

			// make the socket.io connection
			socket.Connect();
		}
        private void connectBt_Click(object sender, RoutedEventArgs e)
        {
            socketIO = new Client(serverUrl.Text);
            socketIO.Message += socketIO_Message;
            socketIO.SocketConnectionClosed += socketIO_SocketConnectionClosed;
            socketIO.Error += socketIO_Error;

            socketIO.On("connect", (message) =>
            {
                Debug.WriteLine("on connect called!!!");
                JObject jo = new JObject();
                jo["publisher"] = "username";
                jo["password"] = "******";
                socketIO.Emit("hConnect", jo);
            });
            socketIO.ConnectAsync();
        }
Exemple #21
0
        private void InitSocket()
        {
            _socket = new Client(txtServerUrl.Text.Trim());

              _socket.Message += (s, a) =>
              {

              };
              _socket.On("player:requestRemotePlay", fn =>
            {

              var trackId = new Regex(@"^spotify:track:", RegexOptions.IgnoreCase).Replace(fn.Json.Args[0].item.url.ToString(), "");
              Spotify.SpotifyHelpers.PlaySong(trackId);
              _currentId = trackId;
              Console.WriteLine("player:requestRemotePlay");
              _counter = 0;

            });

              _socket.On("player:remoteItemStopped", fn =>
            {

              Console.WriteLine("player:remoteItemStopped");

              if (!String.IsNullOrEmpty(_currentId))
              {
            Spotify.SpotifyHelpers.StopPlayback();
            _currentId = null;
            //this.tmrUpdateStatus.Stop();
              }

            });

              Action join = () =>
              {

            _socket.Emit("stream:join", new { stream = txtStreamID.Text.Trim() });
              };
              //join();

            //  _socket.On("reconnect", a => join());

              _socket.Opened += (s, e) => join();
              _socket.Connect();
        }
Exemple #22
0
	public void initialize(){
		socket = new SocketIOClient.Client("http://"+ip+"");
		
		socket.On("connect", (fn) => {
			Debug.Log ("connect - socket");
			
			//Dictionary<string, string> args = new Dictionary<string, string>();
			//List<string> args = new List<string>();
			//args.Add("what's up?");
			//socket.Emit("SEND", args);
			//string valueout;
			//args.TryGetValue("msg", out valueout);
		});
		
		socket.On("keyPressed", (fn) => {

			string data =  (string)fn.Json.args[0];

			string[] dataArray = data.Split(',');
			int millis = int.Parse(dataArray[1]);

			int score = int.Parse(dataArray[2]);

			if(dataArray[0].Equals("0")) manager.reciveLeft(millis, score);
			if(dataArray[0].Equals("1")) manager.reciveDown(millis, score);
			if(dataArray[0].Equals("2")) manager.reciveUp(millis, score);
			if(dataArray[0].Equals("3")) manager.reciveRight(millis, score);
		});

		socket.On("startGame", (fn) => {
			Debug.Log("Gloworbo");
			gameFlowManagerScript.runOnline();
		});
		
		socket.Error+=(sender, e) => {
			Debug.Log("Error "+ e.Message.ToString());
			error = true;
		};

		socket.On("playerLeft", (fn) => {
			Application.LoadLevel(Application.loadedLevel);
		});
		
		if(!error) socket.Connect();
	}
Exemple #23
0
    void Start()
    {
        socket = new SocketIOClient.Client("http://127.0.0.1:80/");
        socket.On("connect", (fn) => {
            Debug.Log("connect - socket");

            Dictionary <string, string> args = new Dictionary <string, string>();
            args.Add("msg", "what's up?");
            socket.Emit("SEND", args);
        });
        socket.On("RECV", (data) => {
            Debug.Log(data.Json.ToJsonString());
        });
        socket.Error += (sender, e) => {
            Debug.Log("socket Error: " + e.Message.ToString());
        };
        socket.Connect();
    }
Exemple #24
0
    // Use this for initialization
    void Start()
    {
        socket = new SocketIOClient.Client("http://127.0.0.1:3000/");

        socket.On("connect", (fn) => {
            //Debug.Log ("connect - socket");

            //Dictionary<string, string> args = new Dictionary<string, string>();
            //args.Add("send message", "what's up?");

            socket.Emit("send message", "yo new albert socket in town");

            //socket.Emit("send message", "yo new socket in town");

            socket.Message += SocketMessage;
        });



        socket.Connect();
    }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            _client = new Client("http://10.10.35.166:8080");//http://10.30.200.81:1337

            _client.On("open", message =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    Chat.Text += "Connection opened\n";
                });
            });

            _client.On("PlayerJoin", message =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    Chat.Text += message.Json.Args[0] + "\n";
                });
            });
        }
Exemple #26
0
        public void StartConnection(string Ip)
        {
            Console.WriteLine("Starting TestSocketIOClient Example...");

            client = new Client(Ip);

            // register for 'connect' event with io server
            client.On("succesfull", (data) =>
            {
                //MessageBox.Show("asd");
            });

            // register for 'update' events - message is a json 'Part' object
            client.On("playerJoined", (data) =>
            {
                //MessageBox.Show(data.RawMessage);
                //SimpleJson.SimpleJson.DeserializeObject<Player>(data.RawMessage);
            });

            // make the socket.io connection

            client.Connect();
        }
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     user = "******";
     MyForm = new Form1();
     temp = new Form2();
     Application.Run(temp);
     try
     {
         socket = new Client(ip.ToString());
         socket.On("txt", (data) =>
         {
             //MessageBox.Show(data.RawMessage);
             String msg = data.Json.Args[0].ToString();
             Console.Write(msg);
             MyForm.update(msg);
             //MessageBox.Show(msg, "Received Data");
         });
         socket.Connect();
          }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString(),"Something Went Wrong!!");
         Application.Exit();
     }
     if (socket.ReadyState.ToString() == "Connecting")
     {
         userset();
         Application.Run(MyForm);
     }
     else
     {
         MessageBox.Show("Failed To Connect To Server!", "Error!");
         Application.Exit();
     }
 }
Exemple #28
0
        public void InitializeSocket()
        {
            if(_client != null)
                _client.Close();
            _client = new Client(@"https://socketio.mtgox.com");
            _client.Message += SocketClientMessage;
            _client.Error += SocketClientError;
            _client.SocketConnectionClosed += SocketClientConnectionClosed;

            if (ValidApiKey)
            {
                SubscribeUserChannel subUser = new SubscribeUserChannel(GetIdKey());
                JSONMessage userMsg = new JSONMessage(subUser, endpoint: "/mtgox") { Json = new JsonEncodedEventMessage("message", subUser) };
                SubscribeLag subLag = new SubscribeLag();
                JSONMessage lagMsg = new JSONMessage(subLag, endpoint: "/mtgox") { Json = new JsonEncodedEventMessage("message", subLag) };
                _client.On("connect", data =>
                {
                    _client.Send(userMsg);
                    _client.Send(lagMsg);
                });
            }

            _client.Connect("/mtgox");
        }
 private void InitSocket()
 {
     this.socket = new Client(this.Url);
     this.socket.RetryConnectionAttempts = int.MaxValue;
     this.socket.ConnectionReconnect += new EventHandler((sender, args) =>
         {
             this.RedoSubscription();
         });
     this.socket.Connect();
 }
        void similar_Example()
        {
            var socket = new Client("http://127.0.0.1:3000/"); // url to the nodejs
            socket.Connect();
            socket.On("connect", (fn) =>
            {
                Console.WriteLine("\r\nConnected event...\r\n");
            });

            var logger = socket.Connect("/logger"); // connect to the logger ns
            logger.On("traceEvent", (eventLog) =>
            {
                // do something with eventLog
            });
        }
 void timeout_Elapsed(object state)
 {
     if (connTimeoutTimer != null)
     {
         connTimeoutTimer.Cancel();
         connTimeoutTimer = null;
     }
     updateStatus(ConnectionStatus.DISCONNECTED, ConnectionErrors.CONN_TIMEOUT, null);
     if (socketIO.IsConnected)
         socketIO.Close();
     socketIO = null;
 }
 void socketIO_Error(object sender, ErrorEventArgs e)
 {
     if (socketIO != null && socketIO.IsConnected)
     {
         socketIO.Close();
         this.Close();
     }
     socketIO = null;
     string errorMsg = null;
     if (e != null)
     {
         errorMsg = e.Exception.ToString();
     }
     if (connTimeoutTimer != null)
     {
         connTimeoutTimer.Cancel();
         connTimeoutTimer = null;
     }
     Debug.WriteLine("[SOCKET_IO]: socketIO Error ");
     updateStatus(ConnectionStatus.DISCONNECTED, ConnectionErrors.TECH_ERROR, errorMsg);
 }
Exemple #33
0
    private void CreateSocket()
    {
        socket = new SocketIOClient.Client("http://127.0.0.1:3000/");
        socket.On("connect", (fn) => {
            Debug.Log("connect - socket");

            Dictionary <string, string> args = new Dictionary <string, string>();
            args.Add("pseudo", "toto");
            args.Add("password", "tata");
            socket.Emit("authentication", args);
            socket.On("unauthorized", (data) => {
                Debug.Log("unauthorized");
                socket.Close();
            });
            socket.On("authenticated", (data) => {
                Debug.Log("authenticated");
                socket.On("result", (result) =>
                {
                    Debug.Log("command result = " + result);
                });
                socket.On("lobbylist", (result) =>
                {
                    Debug.Log("lobby list = " + result.Json.ToJsonString());
                });
                socket.On("lobbycreated", (result) =>
                {
                    Debug.Log("lobby created // " + result.Json.ToJsonString() + "//");
                });
                socket.On("lobbyjoined", (result) =>
                {
                    Debug.Log("lobby joined // " + result.Json.ToJsonString() + "//");
                });
                socket.On("lobbyleft", (result) =>
                {
                    Debug.Log("lobby left");
                });
                socket.On("readyset", (result) =>
                {
                    Debug.Log("readyset");
                });
                socket.On("goingame", (result) =>
                {
                    Debug.Log("goingame");
                });
                socket.On("unreadyset", (result) =>
                {
                    Debug.Log("unreadyset");
                });
                socket.On("cantunready", (result) =>
                {
                    Debug.Log("cantunready");
                });
                socket.On("countdown", (result) =>
                {
                    Debug.Log("countdown");
                });
                socket.On("playerjoined", (result) =>
                {
                    Debug.Log("playerjoined");
                });
                socket.On("playerleft", (result) =>
                {
                    Debug.Log("playerleft");
                });
                socket.On("opponentreadyup", (result) =>
                {
                    Debug.Log("opponentreadyup");
                });
                socket.On("opponentunready", (result) =>
                {
                    Debug.Log("opponentunready");
                });
                socket.On("update", (result) =>
                {
                    Debug.Log("update");
                });
                socket.On("gameover", (result) =>
                {
                    Debug.Log("gameover");
                });
                socket.On("result", (result) =>
                {
                    Debug.Log("result");
                });
            });
        });

        socket.Error += (sender, e) => {
            Debug.Log("socket Error: " + e.Message.ToString());
        };
    }
Exemple #34
0
    private void CreateSocket(string name, string password)
    {
        _socket = new SocketIOClient.Client("http://" + _baseAddress + "/ ");
        _socket.On("connect", (fn) =>
        {
            Debug.Log("connect - socket");

            Dictionary <string, string> args = new Dictionary <string, string>();
            args.Add("pseudo", name);
            args.Add("password", password);
            _socket.Emit("authentication", args);
            _socket.On("unauthorized", (data) =>
            {
                Debug.Log("unauthorized");
                if (Unauthorized != null)
                {
                    Unauthorized(JSON.Parse(data.Encoded));
                }
                _socket.Close();
            });
            _socket.On("authenticated", (data) =>
            {
                Debug.Log("authenticated");
                if (Authenticated != null)
                {
                    Authenticated(JSONNode.Parse(data.Encoded));
                }

                _socket.On("lobbylist", (result) =>
                {
                    if (LobbyList != null)
                    {
                        JSONNode resultjson    = JSONNode.Parse(result.Encoded);
                        JSONArray arguments    = resultjson["args"].AsArray;
                        JSONArray actualresult = arguments[0].AsArray;
                        LobbyList(actualresult);
                    }
                });
                _socket.On("lobbycreated", (result) =>
                {
                    if (LobbyCreated != null)
                    {
                        LobbyCreated(JSONNode.Parse(result.Encoded));
                    }
                });
                _socket.On("lobbyfull", (result) =>
                {
                    if (LobbyFull != null)
                    {
                        LobbyFull(JSONNode.Parse(result.Encoded));
                    }
                });
                _socket.On("lobbyjoined", (result) =>
                {
                    if (LobbyJoined != null)
                    {
                        JSONNode resultjson = JSONNode.Parse(result.Encoded)["args"][0];
                        LobbyJoined(resultjson);
                    }
                });
                _socket.On("lobbyleft", (result) =>
                {
                    if (LobbyLeft != null)
                    {
                        LobbyLeft(JSONNode.Parse(result.Encoded));
                    }
                });
                _socket.On("readyset", (result) =>
                {
                    if (ReadySet != null)
                    {
                        JSONNode resultjson = JSONNode.Parse(result.Encoded)["args"][0];
                        ReadySet(resultjson);
                    }
                });
                _socket.On("goingame", (result) =>
                {
                    if (GoInGame != null)
                    {
                        GoInGame(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("unreadyset", (result) =>
                {
                    if (UnReadySet != null)
                    {
                        UnReadySet(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("cantunready", (result) =>
                {
                    if (CantUnready != null)
                    {
                        CantUnready(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("countdown", (result) =>
                {
                    if (Countdown != null)
                    {
                        Countdown(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("playerjoined", (result) =>
                {
                    if (PlayerJoined != null)
                    {
                        PlayerJoined(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("playerleft", (result) =>
                {
                    if (PlayerLeft != null)
                    {
                        PlayerLeft(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("opponentreadyup", (result) =>
                {
                    if (OpponentReadyUp != null)
                    {
                        OpponentReadyUp(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("opponentunready", (result) =>
                {
                    if (OpponentUnready != null)
                    {
                        OpponentUnready(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("update", (result) =>
                {
                    if (Update != null)
                    {
                        Update(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("gameover", (result) =>
                {
                    if (Gameover != null)
                    {
                        Gameover(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
                _socket.On("result", (result) =>
                {
                    if (Result != null)
                    {
                        Result(JSONNode.Parse(result.Encoded)["args"][0]);
                    }
                });
            });
        });

        _socket.Error += (sender, e) => {
            Debug.Log("socket Error: " + e.Message.ToString());
            if (Error != null)
            {
                Error(e.Message.ToString());
            }
        };
    }
        void explicit_Example()
        {
            var socket = new Client("http://127.0.0.1:3000/"); // url to the nodejs
            socket.Connect();
            socket.Connect("/logger");

            // EventMessage by namespace
            socket.On("traceEvent", "/logger", (eventLog) =>
            {
                Console.WriteLine("recv #1 [logger].[traceEvent] : {0}\r\n", eventLog.Json.GetFirstArgAs<EventLog>().ToJsonString());
            });
            socket.Emit("messageAck", new { hello = "papa" }, "/logger");
        }
Exemple #36
0
 private static void emit(Client cli, string chan, object obj, string gameServer)
 {
     cli.Emit("Gateway.Message", new { channel = chan, content = obj, gameServer=gameServer });
 }
        //Free the resources
        private void closeSocketIO()
        {
            if (this.socket != null) {
                this.socket.Opened -= this.SocketOpened;
                this.socket.Message -= this.SocketMessage;
                this.socket.SocketConnectionClosed -= this.SocketConnectionClosed;
                this.socket.Error -= this.SocketError;

                this.socket = null;
            }
        }
Exemple #38
0
        private static void Target(object parameters)
        {
            var options = (ThreadParams)parameters;
            Random rand = new Random(options.Seed);

            if (options.State == ThreadState.CreateGame)
            {
                Thread.Sleep(rand.Next(0, 500));
            }

            if (options.State == ThreadState.JoinGame)
            {
                Thread.Sleep(rand.Next(1500, 2500));
            }

            Console.WriteLine(string.Format("Begin {0}", options.State));
            string ip=null;

            WebClient client = new WebClient();
            ip = client.DownloadString("http://50.116.22.241:8844");

            var socket = new Client(ip); // url to nodejs
            socket.Opened += SocketOpened;
            socket.Message += SocketMessage;
            socket.SocketConnectionClosed += SocketConnectionClosed;
            socket.Error += SocketError;
            string gameServer=null;
            string roomID = null;
            // register for 'connect' event with io server

            Dictionary<string, Action<dynamic>> dct = new Dictionary<string, Action<dynamic>>();

            socket.On("Client.Message", (fn) =>
                                            {
                                                var cn = fn.Json.Args[0].channel.Value;
                                                var cnt = fn.Json.Args[0].content;

                                                dct[cn](cnt);

                                            });

            dct.Add("Area.Game.AskQuestion", (fn) =>
            {
                Thread.Sleep(rand.Next(300, 800));
                Console.WriteLine("asked: " + "  " + options.UserName);
                if (socket == null) return;
                try
                {
                    emit(socket, "Area.Game.AnswerQuestion", new { answer = 1, roomID }, gameServer);
                }catch(Exception)
                {
                    Console.WriteLine("failed for some reason");
                }
            });

            dct.Add("Area.Game.UpdateState", (fn) =>
            {

            });

            dct.Add("Area.Game.RoomInfo", (fn) =>
                                                {
                                                    roomID = fn.roomID.ToString();
                                                    gameServer = fn.gameServer;
                                                });

            bool gameover = false;
            dct.Add("Area.Game.GameOver", (fn) =>
                                              {
                                                  socket.Close();
                                                  socket.Dispose();
                                                  gameover = true;

                                              });
            dct.Add("Area.Game.RoomInfos", (data) =>
                                                 {

                                                     foreach (var room in data.Children())
                                                     {
                                                         var plys = 0;
                                                         foreach (var child in room["players"].Children())
                                                         {
                                                             plys++;
                                                         }
                                                         if (room["started"].Value)
                                                         {
                                                             continue;
                                                         }
                                                         gameServer = room["gameServer"].Value;
                                                         switch (options.State)
                                                         {
                                                             case ThreadState.JoinGame:
                                                                 roomID = room["roomID"].Value;
                                                                 emit(socket, "Area.Game.Join", new { user = new { userName = options.UserName }, roomID = room["roomID"].Value }, gameServer);

                                                                 if (plys + 1 >= options.MaxUsers)
                                                                 {
                                                                     Thread.Sleep(rand.Next(750, 1250));
                                                                     emit(socket, "Area.Game.Start", new { roomID = room["roomID"].Value }, gameServer);
                                                                     return;
                                                                 }
                                                                 return;
                                                                 break;
                                                             default:
                                                                 throw new ArgumentOutOfRangeException();
                                                         }
                                                     }

                                                     Thread.Sleep(rand.Next(600, 900));
                                                     emit(socket, "Area.Game.GetGames", true, gameServer);
                                                 });
            dct.Add("Area.Game.Started", (fn) =>
            {

            });

            // make the socket.io connection
            socket.Connect();

            socket.Emit("Gateway.Login", new {userName = options.UserName + " " + Guid.NewGuid().ToString()});

            switch (options.State)
            {
                case ThreadState.JoinGame:
                    emit(socket, "Area.Game.GetGames", true, gameServer);
                    break;
                case ThreadState.CreateGame:
                    Console.WriteLine( "Created");

                    emit(socket, "Area.Game.Create", new { gameName = "Sevens", name = "game " + Guid.NewGuid().ToString()  , user = new { name = options.UserName } }, gameServer);

                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            while (!gameover)
            {
                Thread.Sleep(1000);
            }
        }
        public void SubscribeToRoutes(Client socket)
        {
            socket.On("connect", (fn) =>
            {
                Console.WriteLine("\r\nConnected ...\r\n");
                TellServerAboutSensor();
            });
            socket.On("getFrameFromSensor", (fn) =>
            {
                Console.WriteLine("GOT A CALIBRATION CALL");
                BroadcastCapsule broadcastData;
                
                if (kinectSensor != null)
                {
                    broadcastData = new BroadcastCapsule("setCalibrationFrame", depthRenderer2.frameData);
                }
                else
                {
                    //no Kinect sensor detected? error?
                    broadcastData = new BroadcastCapsule("setCalibrationFrame", "");
                }

                socket.Emit("broadcast", broadcastData);
            });
            socket.On("setTranslateRule", (fn) =>
            {
                var results = JsonConvert.DeserializeObject<dynamic>(fn.Json.ToJsonString());
                Console.WriteLine(results);
                Console.WriteLine(fn.Json.Args[0].startingLocation);
                translateRule = new TranslateRule((float)fn.Json.Args[0].degree, (float)fn.Json.Args[0].xDistance, (float)fn.Json.Args[0].zDistance, (float)fn.Json.Args[0].xSpaceTransition, (float)fn.Json.Args[0].zSpaceTransition, JsonConvert.DeserializeObject<Point3D>(fn.Json.Args[0].startingLocation + ""));

                //update rule display on UI
                /*
                lblCalibrationOrientation.Content = "Change in Orientation: " + translateRule.changeInOrientation;
                lblCalibrationPoint.Content = "dX, dZ: " + translateRule.dX + ", " + translateRule.dZ;
                lblCalibrationTranslation.Content = "xTran, zTran: " + translateRule.xSpace + ", " + translateRule.zSpace;
                lblCalibrationStartingLocation.Content = "Starting Location: " + translateRule.startingLocation.X + ", "
                    + translateRule.startingLocation.Y + ", " + translateRule.startingLocation.Z;

                Console.WriteLine("New calibration rule:");
                Console.WriteLine(JObject.FromObject(translateRule).ToString());
                 */
                updateTranslateRuleLabels();
            });

            socket.On("resetRule", (fn) =>
            {
                translateRule = new TranslateRule(0, 0, 0, 0, 0, new Point3D(0, 0, 0));
                Console.WriteLine("Reset calibration rule:");
                Console.WriteLine(JObject.FromObject(translateRule).ToString());
                updateTranslateRuleLabels();
            });
        }
        void StatusSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (!isValidInput()) { return; }

            if (StatusSubmit.Content.Equals("Connect")) //Users wants to connect
            {
                //Connect to server//      
                string address = "http://" + ServerTextBox.Text + ":" + PortTextBox.Text + "/";
                Console.WriteLine("Connecting to: " + address);
                socket = new Client(address);
                socket.Connect();

                //Debug, check if sensor still exists// Disable for Kinect2
                Console.WriteLine("Sensor: " + kinectSensor);
                ///////////////////////////////////////
                TimeSpan maxDuration = TimeSpan.FromMilliseconds(1000);
                Stopwatch sw = Stopwatch.StartNew();

                while (sw.Elapsed < maxDuration && !socket.IsConnected)
                {
                    // wait for connected
                }

                if (socket.IsConnected)
                {
                    StatusSubmit.Content = "Disconnect";
                    StatusLabel.Text = "Connected";

                    if (TellServerAboutSensor())
                    {
                        //sensor registered with server
                    }
                    else
                    {
                        //no sensor was registered with server!
                    }
                    socket.Message += new EventHandler<MessageEventArgs>(socket_Message);
                    SubscribeToRoutes(socket);
                }
                else
                {
                    Console.WriteLine("Device never registered with server!");
                }
            }
            else //Users wants to disconnect
            {
                socket.Close();
                if (!socket.IsConnected) //replace true with condition for successful disconnect
                {
                    //disconnected, cleanup
                    StatusSubmit.Content = "Connect";
                    StatusLabel.Text = "Disconnected";
                }
                else
                {
                    MessageBox.Show("Server failed to disconnect properly.");
                }
            }
        }
        //哭了,貌似socketIO中on事件里会发生这个闹心的问题啊
        //他的相当于另起一个线程,然后里边的东西变成了局部变量,不能改变这个class的值啊  疯了!!!
        //那怎么玩啊、、弄个static试试
        //nice啊 静态也不行。哭了哭了 这次真哭了!
        private void connectBt_Click(object sender, RoutedEventArgs e)
        {
            //socketIO = new Client(serverUrl.Text);
            //socketIO = new Client("http://168.63.151.29:3000");
            this.connectBt.IsEnabled = false;
            socketIO = new Client("http://test.twtstudio.com:3000");
            socketIO.Message += socketIO_Message;
            socketIO.SocketConnectionClosed += socketIO_SocketConnectionClosed;
            socketIO.Error += socketIO_Error;

            socketIO.On("connect", (message) =>
            {

                Debug.WriteLine("on connect called!!!");
                JObject jo = new JObject();
                jo["username"] = "******";
                jo["password"] = "******";
                socketIO.Emit("hConnect", jo);

            });

            socketIO.On("a", async (message) =>
            {
                Debug.WriteLine("start listening");
                Debug.WriteLine(message.Json.ToJsonString());
                await SampleDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    /*//定义一个JSON字符串
                    string jsonText = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aaa2','b':'bbb2','c':'ccc2'}]";
                    //反序列化JSON字符串*/
                    //JArray ja = (JArray)JsonConvert.DeserializeObject(message.Json.ToJsonString());
                   // JArray ja = (JArray)JsonConvert.DeserializeObject(jsonText);
                    //将反序列化的JSON字符串转换成对象
                    JObject o = (JObject)JsonConvert.DeserializeObject(message.Json.ToJsonString());
                    //读取对象中的各项值
                    JArray jb = (JArray)JsonConvert.DeserializeObject(o["args"].ToString());

                    JObject ob = (JObject)jb[0];

                    JObject oc = (JObject)ob["mes"];

                    //Console.WriteLine(ja[1]["a"]);

                   // ChangedEventHandler(message.Json.ToJsonString());

                    if(oc["a"] != null )
                        ChangedEventHandler(oc["a"].ToString());
                    //{"name":"a","args":[{"mes":{"username":"******","password":"******"}}]}
                });
            });

            socketIO.ConnectAsync();
        }