public On ( string eventName, Action |
||
eventName | string | |
action | Action |
|
Результат | void |
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" }); }
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(); }
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(); }
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(); } }
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(); }
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(); }
//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 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"); }
//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(); }
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(); }
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(); }
static void Main(string[] args) { Console.WriteLine("Starting TestSocketIOClient Example..."); var socket = new Client("http://192.168.80.1:3000/"); // url to nodejs socket.Opened += (a, b) => { Console.WriteLine("Opened"); }; socket.Message += (a, b) => { Console.WriteLine("Message"); }; socket.SocketConnectionClosed += (a, b) => { Console.WriteLine("SocketConnectionClosed"); }; socket.Error += (a, b) => { Console.WriteLine("Error"); }; // register for 'connect' event with io server socket.On("connect", (fn) => { Console.WriteLine("socket.On(connect)"); // emit Json Serializable object, anonymous types, or strings var msg = new Message() { body = "Hello world!" }; socket.Emit("msg", msg); }); // register for 'update' events - message is a json 'Part' object socket.On("msg", (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 var msg = data.Json.GetFirstArgAs<Message>(); Console.WriteLine(">> {0}", msg.body); }); // make the socket.io connection socket.Connect(); while (true) { Console.Write("> "); var txt = Console.ReadLine(); var msg = new Message { body = txt }; socket.Emit("msg", msg); } }
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"); }
// 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(); }
// 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"; }); }); }
// 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(); }
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(); }
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(); }
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(); }
// 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(); }
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(); } }
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"); }
public void Start(string nodeServerUrl) { if (log.IsDebugEnabled) { log.Debug("Start"); } Console.WriteLine("Starting SocketIoProxy..."); socket = new Client(nodeServerUrl); // url to the nodejs / socket.io instance socket.Opened += socket_Opened; socket.Message += socket_OnMessage; socket.SocketConnectionClosed +=socket_SocketConnectionClosed; socket.Error += socket_Error; socket.On("connect", (data) => { if (log.IsDebugEnabled) { log.Debug("Start.Connect.data." + (data == null ? "null" : data.JsonEncodedMessage.ToJsonString())); } Console.WriteLine("\r\nSocketIoProxy.connect: {0}", data.JsonEncodedMessage.ToJsonString()); }); socket.On("clientEventInternal", (data) => { ClientEvent clientEvent = null; if (data != null && data.JsonEncodedMessage != null && data.JsonEncodedMessage.Args != null && data.JsonEncodedMessage.Args.Length > 0) { try { clientEvent = ClientEvent.FromJsonString(data.JsonEncodedMessage.Args[0].ToString()); } catch (Exception ex) { throw ex; } } if (clientEvent != null && clientEvent.ClientData != null) { //if it's a connect event, then create the client if (!string.IsNullOrEmpty(clientEvent.ClientData.EventName) && clientEvent.ClientData.EventName.ToLower() == "connect") { if (log.IsDebugEnabled) { log.Debug("Start.clientEventInternal.connect.clientEvent." + (clientEvent == null ? "null" : clientEvent.ToJsonString())); } Business.Entity.Client.CreateFromClientEvent(clientEvent, Business.Entity.Client.ClientStateEnum.Available); //socket.Emit("clientRequestInternal", new { SessionNodeId = clientEvent.SessionNodeId, Color = "Blue" }); } else { if (log.IsDebugEnabled) { log.Debug("Start.clientEventInternal." + clientEvent.ClientData.EventName + ".clientEvent." + (clientEvent == null ? "null" : clientEvent.ToJsonString())); } } } else { if (log.IsDebugEnabled) { log.Debug("Start.clientEventInternal.UnableToDeserialize.data." + (data == null ? "null" : data.JsonEncodedMessage.ToJsonString())); } Console.WriteLine("\r\nSocketIoProxy.clientEvent (unable to deserialize): {0}", data.JsonEncodedMessage.ToJsonString()); } }); socket.On("clientResponseInternal", (data) => { ClientResponse clientResponse = null; if (data != null && data.JsonEncodedMessage != null && data.JsonEncodedMessage.Args != null && data.JsonEncodedMessage.Args.Length > 0) { try { clientResponse = ClientResponse.FromJsonString(data.JsonEncodedMessage.Args[0].ToString()); } catch (Exception ex) { throw ex; } } if (clientResponse != null && clientResponse.ClientData != null) { if (log.IsDebugEnabled) { log.Debug("Start.clientResponseInternal.HandleResponse.clientResponse." + (clientResponse == null ? "null" : clientResponse.ToJsonString())); } clientResponse.HandleResponse(); //socket.Emit("clientRequestInternal", new { SessionNodeId = clientEvent.SessionNodeId, Color = "Blue" }); } else { if (log.IsDebugEnabled) { log.Debug("Start.clientResponseInternal.UnableToDeserialize.data." + (data == null ? "null" : data.JsonEncodedMessage.ToJsonString())); } Console.WriteLine("\r\nSocketIoProxy.clientResponse (unable to deserialize): {0}", data.JsonEncodedMessage.ToJsonString()); } }); socket.On("serverRequestInternal", (data) => { Console.WriteLine("\r\nSocketIoProxy.serverRequest: {0}", data.JsonEncodedMessage.ToJsonString()); ClientEvent clientEvent = null; if (data != null && data.JsonEncodedMessage != null && data.JsonEncodedMessage.Args != null && data.JsonEncodedMessage.Args.Length > 0) { try { clientEvent = ClientEvent.FromJsonString(data.JsonEncodedMessage.Args[0].ToString()); } catch (Exception ex) { throw ex; } } if (clientEvent != null) { if (log.IsDebugEnabled) { log.Debug("Start.serverRequestInternal.EmitServerRequest.clientEvent." + (clientEvent == null ? "null" : clientEvent.ToJsonString())); } socket.Emit("serverRequest", new { SessionNodeId = clientEvent.SessionNodeId, Color = "Red" }); } else { if (log.IsDebugEnabled) { log.Debug("Start.serverRequestInternal.UnableToDeserialize.data." + (data == null ? "null" : data.JsonEncodedMessage.ToJsonString())); } } }); socket.Connect(); }
// Use this for initialization private void InitSocket() { client = new Client("http://192.168.1.50:5000"); client.Error += SocketError; client.Message += SocketMessage; client.On ("connect", "/events", (fn) => { EventOpenParachute(); EventWaterSplasherOn(); EventFanSpeed(100); EventWaterSplasherOff(); }); client.On ("raspiStartJumpEvent", "/events", (data) => { Debug.LogError("TODO: Hook up start"); EventJumpStarted(); //EventLanding(); }); client.On ("raspiPlayerReadyEvent", "/events", (data) => { EventUnityReady(); }); socket = client.Connect ("/events"); }
public void Execute(bool startNovelty = false) { Console.WriteLine("Starting TestSocketIOClient Example..."); socket = new Client("http://localhost:3000/"); // url to the nodejs / socket.io instance socket.Opened += SocketOpened; socket.Message += SocketMessage; socket.SocketConnectionClosed += SocketConnectionClosed; socket.Error += SocketError; // register for 'connect' event with io server socket.On("connect", (fn) => { Console.WriteLine("\r\nConnected event...\r\n"); Console.WriteLine("Connected To Socket Object"); //begin our threaded novelty evaluations on connect if(startNovelty) simpleExperiment.StartNoveltyEvaluations(); }); socket.On("toggleNetwork", (fn) => { print.WriteLine("Incoming select: " + fn.Json.ToJsonString()); //we see an incoming request for selection long selectionID = (long)fn.Json.Args[0]; //we have the ID, now we must do some toggling //we could call the evolution manager directly, but perhaps it's best to separate these objects? In case there are many experiements or someting? //or maybe the experiment wants to not the selection information bool toggle = simpleExperiment.toggleNetwork(selectionID); if (toggle) print.WriteLine("Successful toggle, as suspected"); EvolutionManager eManager = EvolutionManager.SharedEvolutionManager; string isSelected = string.Format("{0}:::{1}+[{2}]", (int)SocketIOMessageTypes.ACK, fn.AckId, JsonConvert.SerializeObject(eManager.isSelected(selectionID))); print.WriteLine("Responding to toggleNetwork with: " + JsonConvert.SerializeObject(eManager.isSelected(selectionID))); socket.Send(isSelected); }); //you simply make a request for the next body, no socket.On("getBodies", (fn) => { if (fn.Json.Args.Length > 0) { //we accept a parameter describing the number of desired bodies int numberOfBodies = (int)fn.Json.Args[0]; //We must generate our collection of bodies and send them back in a JSON object string[] bodies = simpleExperiment.fetchBodies(numberOfBodies); //we have all of our bodies, we must send them back now! string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodies)); //now return information to our socket socket.Send(bodiesMessage); } }); socket.On("getGenomes", (fn) => { if (fn.Json.Args.Length > 0) { //we accept a parameter describing the number of desired bodies JArray con = (JArray)fn.Json.Args[0]; List<long> genomeIDs = new List<long>(); foreach (var idString in con) { long genomeID; if (long.TryParse(idString.ToString(), out genomeID)) { //Console.WriteLine("Genomeid: " + genomeID); genomeIDs.Add(genomeID); } else { throw new Exception("Failure to send appropriate genomeID"); } } try { //We must find our collection of bodies and send them back in a JSON object Dictionary<long, string> bodies = simpleExperiment.fetchBodiesFromIDs(genomeIDs); //we have all of our bodies, we must send them back now! string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodies)); print.WriteLine("Sending bodies: " + JsonConvert.SerializeObject(bodies.Keys)); //now return information to our socket socket.Send(bodiesMessage); } catch (Exception e) { //we failed to fetch the bodies, throw an error, this is some serious stuff! Console.WriteLine("Failed to fetch bodies and send response"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); throw e; } } }); socket.On("getBest", (fn) => { if (fn.Json.Args.Length > 0) { long lastQueryTime = (long)fn.Json.Args[0]; //long.TryParse(fn.Json.Args[0], out lastQueryTime); //get our best bodies var bodyAndTime = simpleExperiment.fetchBestBodies(lastQueryTime); //we have all of our bodies, we must send them back now! string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodyAndTime)); print.WriteLine("Sending best: " + JsonConvert.SerializeObject(bodyAndTime.Second.Keys)); //now return information to our socket socket.Send(bodiesMessage); } }); socket.On("ping", (fn) => { print.WriteLine("Incoming Ping: " + fn.Json.ToJsonString()); int value = (int)fn.Json.Args[0]; value = value +1; //string jSon = SimpleJson.SimpleJson.SerializeObject(net); string jSon = simpleExperiment.fetchNextBodyJSON(); //Dictionary<string, object> stuff =new Dictionary<string,object>(); //stuff.Add("c#says", "pong"); //stuff.Add("valuePlusOne", value); //string data = SimpleJson.SimpleJson.SerializeObject(stuff); //string.Format("{\"{0}\": \"{1}\", \"{2}\": {3} }", "c#Says", "pong", "value", value); string tosend = string.Format("{0}:::{1}+[{2}]", (int)SocketIOMessageTypes.ACK, fn.AckId, jSon); print.WriteLine("Responding to ping with: " + jSon); socket.Send(tosend);//new AckMessage() { AckId = fn.AckId, MessageText = "pong" }); }); socket.On("runFullPCA", (fn) => { int xBins, yBins, genomeSelector; double topPercent; bool firstBehavior; bool.TryParse(fn.Json.Args[0], out firstBehavior); int.TryParse(fn.Json.Args[1], out xBins); int.TryParse(fn.Json.Args[2], out yBins); int.TryParse(fn.Json.Args[3], out genomeSelector); double.TryParse(fn.Json.Args[4], out topPercent); //want to send in custom params for selecting what method to grab genomes (or to send a genome array) //if (fn.Json.Args.Length > 0) //{ // //we accept a parameter describing the number of desired bodies // JArray con = (JArray)fn.Json.Args[3]; // Create new stopwatch Stopwatch stopwatch = new Stopwatch(); // Begin timing stopwatch.Start(); //grab ALL of our saved genomes, and make sure they are unique individuals //we group them by a genome ID, then we select the first object in the group, voila, distinct! List<NeatGenome> allGenomes; switch(genomeSelector) { case 0: allGenomes = simpleExperiment.fetchAllGenomes().GroupBy(g => g.GenomeId).Select(group => group.First()).ToList(); break; case 1: allGenomes = simpleExperiment.fetchBestGenomes(topPercent).GroupBy(g => g.GenomeId).Select(group => group.First()).ToList(); break; default: allGenomes = simpleExperiment.fetchAllGenomes().GroupBy(g => g.GenomeId).Select(group => group.First()).ToList(); break; } EvolutionManager.SharedEvolutionManager.saveGenomes(allGenomes); // Begin timing stopwatch.Stop(); Console.WriteLine("Fetch Genomes: " + stopwatch.ElapsedMilliseconds); var uidAndPoints = runPCA(allGenomes,firstBehavior, xBins, yBins); try { //we have all of our bodies, we must send them back now! string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(uidAndPoints)); print.WriteLine("Sending pca analysis for IDs: " + JsonConvert.SerializeObject(uidAndPoints)); //now return information to our socket socket.Send(bodiesMessage); } catch (Exception e) { //we failed to fetch the bodies, throw an error, this is some serious stuff! Console.WriteLine("Failed to fetch bodies and send response"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); throw e; } }); socket.On("runPCA", (empty) => { //we accept a parameter describing the number of desired bodies //JArray con = (JArray)fn.Json.Args[0]; //grab the best individuals (already having been evaluated, we grab their behavior and PCA //get our best bodies List<NeatGenome> topBodyAndTime = simpleExperiment.fetchBestGenomes(.1); var uidAndPoints = runPCA(topBodyAndTime); try{ //we have all of our bodies, we must send them back now! string bodiesMessage = formattedSocketMessage(empty.AckId, JsonConvert.SerializeObject(uidAndPoints)); print.WriteLine("Sending pca analysis for IDs: " + JsonConvert.SerializeObject(uidAndPoints)); //now return information to our socket socket.Send(bodiesMessage); } catch (Exception e) { //we failed to fetch the bodies, throw an error, this is some serious stuff! Console.WriteLine("Failed to fetch bodies and send response"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); throw e; } }); //socket.On("evaluateGenomes", (data) => //{ // print.WriteLine(data); // //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]); //}); // register for 'update' events - message is a json 'Part' object socket.On("update", (data) => { print.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]); }); // register for 'update' events - message is a json 'Part' object socket.On("getArchiveIDs", (data) => { //let's go fetch our novelty ids! List<long> archiveIDs = simpleExperiment.GetNoveltyArchive(); if (archiveIDs != null) { //we have all of our ids, we must send them back now! string bodiesMessage = formattedSocketMessage(data.AckId, JsonConvert.SerializeObject(archiveIDs)); socket.Send(bodiesMessage); } }); // Grabs the current generation ids for viewing purposes! socket.On("getCurrentIDs", (data) => { //let's go fetch our novelty ids! List<long> currentIDs = simpleExperiment.GetMultiCurrentGeneration(); if (currentIDs != null) { //we have all of our ids, we must send them back now! string bodiesMessage = formattedSocketMessage(data.AckId, JsonConvert.SerializeObject(currentIDs)); socket.Send(bodiesMessage); } }); // make the socket.io connection socket.Connect(); }
static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Please specify a stream id and base url"); Console.WriteLine(@"e.g. SpotifyLauncher.exe 5089133484bdc27d64000001 ""http://wordpress.rockpool.local:8046"""); return; } string streamId = args[0]; string url = args[1]; var socket = new Client(url); socket.On("player:requestRemotePlay", fn => { Console.WriteLine("player:requestRemotePlay"); if (fn.Json.Args.Length == 0 || fn.Json.Args[0].item == null || fn.Json.Args[0].item.url == null) { return; } string urlParam = fn.Json.Args[0].item.url.ToString(); var trackId = _reTrack.Replace(urlParam, ""); lock (_sync) { Spotify.SpotifyHelpers.PlaySong(trackId); _currentId = trackId; _counter = 0; _timer.Start(); } }); socket.On("player:requestRemoteStop", fn => { Console.WriteLine("player:requestRemoteStop"); lock (_sync) { if (!String.IsNullOrEmpty(_currentId)) { Spotify.SpotifyHelpers.StopPlayback(); _currentId = null; _timer.Stop(); } } }); socket.Opened += (s, e) => socket.Emit("stream:join", new { stream = streamId }); socket.Connect(); _timer = new System.Timers.Timer(200); _timer.Elapsed += (s, e) => { if (_counter++ < 4) { return; } if (_currentId != null) { lock (_sync) { if (_currentId != null) { var status = Spotify.SpotifyHelpers.GetStatus(); // Console.WriteLine("{0},{1},{2}", status.Track, status.TrackID, _currentId); if (String.IsNullOrEmpty(status.TrackID) || !status.TrackID.EndsWith(_currentId)) { //Console.WriteLine("stop detected"); _timer.Stop(); Spotify.SpotifyHelpers.StopPlayback(); socket.Emit("player:remoteItemStopped", new { stream = streamId }); _currentId = null; Console.WriteLine("player:remoteItemStopped"); } } } } }; while (Console.ReadKey().KeyChar != 'q') ; }
//class Part { PartNumber = "K4P2G324EC", Code = "DDR2", Level = 1 }; public void Execute() { Console.WriteLine("Starting TestSocketIOClient Example..."); var headers = new NameValueCollection { { "Cookie", "SID=7fmir6ps5ksdt9fo1dr76c7to7" } }; //socket = new Client("http://prestashop:8081"); // url to nodejs socket = new Client("https://wsbeta.tradernet.ru:443", WebSocket4Net.WebSocketVersion.Rfc6455, headers); // url to nodejs //http://prestashop:8081/ socket.Opened += SocketOpened; socket.Message += SocketMessage; socket.SocketConnectionClosed += SocketConnectionClosed; socket.Error += SocketError; socket.Connect(); // socket.On("q", (data) => // { // Console.WriteLine(">q", data.RawMessage); // Console.WriteLine(">q", data.Json.ToJsonString()); // }); // // socket.On("sup_updateTransactions", (data) => // { // Console.WriteLine(">sup_updateTransactions", data.RawMessage); // Console.WriteLine(">sup_updateTransactions", data.Json.ToJsonString()); // }); // // socket.On("server_message", (data) => // { // Console.WriteLine("server_message", data); // Console.WriteLine(data); // Console.WriteLine(" raw message: {0}", data.RawMessage); // Console.WriteLine(" string message: {0}", data.MessageText); // Console.WriteLine(" json data string: {0}", data.Json.ToJsonString()); // //Part part = data.Json.GetFirstArgAs<Part>(); // //Console.WriteLine(" Part Level: {0}\r\n", part.Level); // // }); // register for 'connect' event with io server // socket.On("connect", (fn) => // { // Console.WriteLine("Connected event..."); // Console.WriteLine("Emit Part object"); // // // emit Json Serializable object, anonymous types, or strings //// Part newPart = new Part() //// { //// PartNumber = "K4P2G324EC", //// Code = "DDR2", //// Level = 1 //// }; // //socket.Emit("partInfo", newPart); // //socket.Emit("message", new int[] { 372134,371014,157050,371012,371033 }); // socket.Emit("sup_subscribeTransactions", new int[] { 372134,371014,157050,371012,371033 }); // socket.Emit("sup_updateSecurities2", new string[] { "RIH4","SIH4","SRH4","EUH4","BRG4","SBER","RTKM","EDH4","GZH4","GAZPM","GDH4","LKOH","GMKN","ROSN","PLZL","BRF4","GUH4","OMC.US","TXN.US","TYC.US","MAR.US","NKE.US","CTSH.US","CHK.US","GD.US","CHRW.US","KMX.US","RU000A0JQC49","RU000A0JQC56","RU000A0JR0A9","RU000A0JSG43","RU000A0JS546","RU000A0JRHL1","RU000A0JREU9","RU000A0JQYZ8","RU000A0JQZ00","RU000A0JTCM6","RU000A0JUBD5","SU25076RMFS9","SU26207RMFS9","RU000A0JRG44","RU000A0JTX33","SU25077RMFS7","RU000A0JS8R5","RU000A0JU179","RU000A0JU963","SU26212RMFS9","GAZPM","SBER","MGNT","LKOH","GMKN","ROSN","VTBR","URKA","SNGSP","SBERP","RIM4","ESM14.US","UXM4" }); // // }); // socket.Emit("message", new int[] { 372134,371014,157050,371012,371033 }); // socket.Emit("sup_subscribeTransactions", new int[] { 372134,371014,157050,371012,371033 }); // socket.Emit("sup_updateSecurities2", new string[] { "RIH4","SIH4","SRH4","EUH4","BRG4","SBER","RTKM","EDH4","GZH4","GAZPM","GDH4","LKOH","GMKN","ROSN","PLZL","BRF4","GUH4","OMC.US","TXN.US","TYC.US","MAR.US","NKE.US","CTSH.US","CHK.US","GD.US","CHRW.US","KMX.US","RU000A0JQC49","RU000A0JQC56","RU000A0JR0A9","RU000A0JSG43","RU000A0JS546","RU000A0JRHL1","RU000A0JREU9","RU000A0JQYZ8","RU000A0JQZ00","RU000A0JTCM6","RU000A0JUBD5","SU25076RMFS9","SU26207RMFS9","RU000A0JRG44","RU000A0JTX33","SU25077RMFS7","RU000A0JS8R5","RU000A0JU179","RU000A0JU963","SU26212RMFS9","GAZPM","SBER","MGNT","LKOH","GMKN","ROSN","VTBR","URKA","SNGSP","SBERP","RIM4","ESM14.US","UXM4" }); // 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 var logger = socket.Connect("/sup"); // connect to the logger ns socket.Message += SocketMessage; logger.On("sup_updateTransactions", (data) => { Console.WriteLine("t: {0}", data.RawMessage); //Console.WriteLine(">sup_updateTransactions", data.Json.ToJsonString()); }); logger.On("q", (data) => { QuotesUpdateEvent quotesUpdate = data.Json.GetFirstArgAs<QuotesUpdateEvent>(); //Console.WriteLine("q: {0}", data.MessageText); Console.WriteLine(">q: {0}", quotesUpdate); }); 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() // { // PartNumber = "K4P2G324EC", // Code = "DDR2", // Level = 1 // }; //socket.Emit("partInfo", newPart); //socket.Emit("message", new int[] { 372134,371014,157050,371012,371033 }); socket.Emit("sup_subscribeTransactions", new int[] { 372134,371014,157050,371012,371033 }); }); logger.Emit("sup_subscribeTransactions", new int[] { 372134,371014,157050,371012,371033 }); logger.Emit("sup_updateSecurities2", new string[] { "RIH4","SIH4","SRH4","EUH4","BRG4","SBER","RTKM","EDH4","GZH4","GAZPM","GDH4","LKOH","GMKN","ROSN","PLZL","BRF4","GUH4","OMC.US","TXN.US","TYC.US","MAR.US","NKE.US","CTSH.US","CHK.US","GD.US","CHRW.US","KMX.US","RU000A0JQC49","RU000A0JQC56","RU000A0JR0A9","RU000A0JSG43","RU000A0JS546","RU000A0JRHL1","RU000A0JREU9","RU000A0JQYZ8","RU000A0JQZ00","RU000A0JTCM6","RU000A0JUBD5","SU25076RMFS9","SU26207RMFS9","RU000A0JRG44","RU000A0JTX33","SU25077RMFS7","RU000A0JS8R5","RU000A0JU179","RU000A0JU963","SU26212RMFS9","GAZPM","SBER","MGNT","LKOH","GMKN","ROSN","VTBR","URKA","SNGSP","SBERP","RIM4","ESM14.US","UXM4" }); }
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 }); }
public void Execute() { Console.WriteLine("Starting TestSocketIOClient Example..."); //socket = new Client("http://192.168.1.2:8080"); // url to the nodejs / socket.io instance //socket = new Client("http://127.0.0.1:8080"); socket = new Client(Utils.LocalIPAddress()); socket.Opened += SocketOpened; socket.Message += SocketMessage; socket.SocketConnectionClosed += SocketConnectionClosed; socket.Error += SocketError; //MESSAGE _ _ BINDINGS // 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() { PartNumber = "K4P2G324EC", Code = "DDR2", Level = 1 }; //socket.Emit("partInfo", newPart); }); socket.On("question", (fn) => { Console.WriteLine("received question"); if (questionCB != null) { questionCB(fn); } }); socket.On("playerMoveAsked", (fn) => { Console.WriteLine("\nreceived playerMoveAsked"); if (playerMoveCB != null) { playerMoveCB(fn); } }); socket.On("battleResult", (fn) => { Console.WriteLine("received battleResult"); if (battleResultCB != null) { battleResultCB(fn); } }); socket.On("questionAnswered", (fn) => { Console.WriteLine("\nreceived answers to question\n"); if (answersReceivedCB != null) { answersReceivedCB(fn); } }); socket.On("requestIdentity", (mes) => { Console.WriteLine("\r\nrequest ID event...\r\n"); socket.Emit("tableIdentity", new { pseudo = "fack yah !" }); }); socket.On("results", (mes) => { Console.WriteLine("\n results received \n"); if (resultCB != null) { resultCB(mes); } }); socket.On("newPlayer", playerConnectCB); socket.On("majPlayerInfo", (data) => { Console.WriteLine("received MajPlayerInfo"); if (majPlayerInfoCB != null) { majPlayerInfoCB(data); } }); socket.On("captureTerritories", (data) => { Console.WriteLine("received captureTerritories"); if (captureZonesCB != null) { captureZonesCB(data); } }); socket.On("placeCommanders", (data) => { Console.WriteLine("received place commanders"); if (placeCommandersCB != null) { placeCommandersCB(data); } }); // 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 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()); }; }
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(); }
static void connectSocket() { try { socket = new Client(ConfigParam.Rows[0]["Host"].ToString()); socket.Error += socket_Error; socket.Opened += socket_Opened; socket.ConnectionRetryAttempt += socket_ConnectionRetryAttempt; socket.SocketConnectionClosed += socket_SocketConnectionClosed; myForm.Socket = socket; socket.On("welcome", (message) => { //MessageBox.Show(data.RawMessage); String msg = message.Json.Args[0].ToString(); dynamic json = JObject.Parse(msg); Console.Write(json.message); myForm.ConsoleWriteLine(json.message.ToString()); dynamic respon = JObject.Parse("{AppID: '" + ConfigParam.Rows[0]["AppID"].ToString() + "'}"); socket.Emit("regAppID", respon); //MessageBox.Show(msg, "Received Data"); }); socket.On("time", (data) => { //MessageBox.Show(data.RawMessage); String msg = data.Json.Args[0].ToString(); dynamic json = JObject.Parse(msg); Console.Write(json.time); myForm.ConsoleWriteLine(json.time.ToString()); socket.Emit("i am client", "{data: '" + msg + "'}"); //MessageBox.Show(msg, "Received Data"); }); socket.On("dMessage", (data) => { //MessageBox.Show(data.RawMessage); String msg = data.Json.Args[0].ToString(); dynamic json = JObject.Parse(msg); myForm.ConsoleWriteLine(json.message.ToString()); //socket.Emit("i am client", "{data: '" + msg + "'}"); //MessageBox.Show(msg, "Received Data"); }); socket.On("request_transaction", (data) => { String msg = data.Json.Args[0].ToString(); dynamic json = JObject.Parse(msg); myForm.ConsoleWriteLine("Get transaction on date : " + json.date.ToString()); ExecuteCommand("", "request_transaction", ""); }); socket.On("fdCommand", (data) => { String msg = data.Json.Args[0].ToString(); dynamic json = JObject.Parse(msg); myForm.ConsoleWriteLine("command : " + json.command.ToString() + " ; parameter : " + json.parameter.ToString()); //dynamic parameter = JObject.Parse(json.parameter.ToString()); //myForm.ConsoleWriteLine("device : " + parameter.device.ToString()); //Store command to command datatable AddCommandLine(json.commandID.ToString(), json.command.ToString(), json.parameter.ToString(), "not_exec"); ExecuteCommand(json.commandID.ToString(), json.command.ToString(), json.parameter.ToString()); /*dynamic responJson = new JObject(); responJson.commandID = ""; responJson.appID = myForm.getAppID(); responJson.respons = json.command.ToString(); socket.Emit("fdCommandRespons", responJson);*/ }); socket.Connect(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Something Went Wrong!!"); Application.Exit(); } if (socket.ReadyState == WebSocket4Net.WebSocketState.None) { socket.Dispose(); socket.Error -= socket_Error; socket.Opened -= socket_Opened; socket.ConnectionRetryAttempt -= socket_ConnectionRetryAttempt; socket.SocketConnectionClosed -= socket_SocketConnectionClosed; myForm.Socket.Dispose(); myForm.Socket = null; socket = null; connectSocket(); } }
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"); }
static void Main(string[] args) { Console.WriteLine("Starting TestSocketIOClient Example..."); socket = new Client("http://localhost:8008/"); // url to nodejs server socket.Error += SocketError; // register for 'connect' event with io server socket.On("connect", (fn) => { Console.WriteLine("\r\nConnected event...\r\n"); }); socket.On("news", (data) => { Console.WriteLine(" raw message: {0}", data.RawMessage); Console.WriteLine(" string message: {0}", data.MessageText); }); socket.On("acceptPosition", (data) => { var x = ((int) data.Json.Args[0].x.Value); var y = ((int) data.Json.Args[0].y.Value); var point = new System.Drawing.Point(x,y); //Console.WriteLine("external: " + point); SetCursorPos(point.X, point.Y); }); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\r\nPress 'c' to execute checkin event \r\n\t(view socket.io server console window to verify).\r\nPress 'x' to exit."); Console.ResetColor(); // make the socket.io connection socket.Connect(); _hookID = SetHook(_proc); Application.Run(); UnhookWindowsHookEx(_hookID); socket.Dispose(); //Execute(); }
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(); }); }
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()); } }; }
//哭了,貌似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(); }