Connect() public method

public Connect ( ) : IEnumerator
return IEnumerator
Ejemplo n.º 1
0
    // -----------------------------------------------------------------
    /// <summary>
    ///
    /// </summary>
    void Connect()
    {
        ws = new WebSocket (WSAddress);

        ws.OnOpen += (sender, e) => {
            Debug.Log ("<color=lime>WebSocket Open</color>");
        };

        ws.OnMessage += (sender, e) => {

            lock (messageQueue.SyncRoot) {
                try {
                    messageQueue.Enqueue (e.Data.ToString ());
                } catch (System.Exception ex) {
                    Debug.Log (ex.ToString ());
                }
            }

            //Debug.Log ("<color=cyan>WebSocket Message Type: " + e.Type + ", Data: " + e.Data + "</color>");
        };

        ws.OnError += (sender, e) => {
            Debug.Log ("<color=red>WebSocket Error Message: " + e.Message + "</color>");
        };

        ws.OnClose += (sender, e) => {
            Debug.Log ("<color=orange>WebSocket Close</color>");
        };

        ws.Connect ();
    }
    void Connect()
    {
        //接続
        //ポートの指定はしなくても大丈夫だった。80で接続してるはず。
        ws =  new WebSocket(url);

        ws.OnOpen += (sender, e) => {
            //接続したら自分を制御用PCとしてサーバーに教える
            //SendSetPCMessage();
            print("Connected");
        };
        ws.OnMessage += (sender, e) => {
            string s = e.Data;
            //Debug.Log (s);
            Dictionary<string, object> dict = Json.Deserialize (s) as Dictionary<string, object>;
            //Debug.Log (dict["power"].GetType() );
            long val = (long)dict["power"];
            //Debug.Log ("val="+val);
            toColor = GetColor(val/divBy);

            value =  val/divBy;
        };
        ws.Connect();

        ws.OnClose += (sender, e) => {
            print("Closed");
        };

        ws.OnError += (sender, e) => {
            print("Error : " + e.Message);
        };
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Start the Birb Client.
    /// </summary>
    /// <returns>Nothing right now.</returns>
    IEnumerator Start()
    {
        gameStateManager = GetComponent<GameStateManager>();
        Uri server = new Uri("ws://birb.herokuapp.com");
        Uri localhost = new Uri("ws://localhost:5000");
        socket = new WebSocket(server);
        callbacks = new Dictionary<BirbMessageCode, Callback>();
        yield return StartCoroutine(socket.Connect());
        int i = 0;

        // Testing
        //RunUnitTests();

        while (true)
        {
            string reply = socket.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                Process(reply);
            }
            if (socket.Error != null)
            {
                Debug.LogError("Error: " + socket.Error);
                break;
            }
            yield return 0;
        }
        socket.Close();
    }
Ejemplo n.º 4
0
	// Use this for initialization
	IEnumerator Start () {
		WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:8080/websocket"));
		yield return StartCoroutine(w.Connect());

		int i = 0;
		w.SendString(PackMessage("Hi there", i));
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Message msg = UnpackMessage (reply);
				Debug.Log ("Received: " + msg.msg + ", " + msg.no);
				w.SendString (PackMessage ("Hi there", i));
			}
			if (w.error != null)
			{
				Debug.LogError ("Error: " + w.error);
				break;
			}

			++i;

			yield return 0;
		}
		w.Close();
	}
Ejemplo n.º 5
0
 void InitWebSocket()
 {
     _ws = new WebSocket ("wss://echo.websocket.org/");
     _ws.OnMessage += MessageCallback;
     _ws.OnError += ErrorCallback;
     _ws.Connect ();
 }
 public void Connect()
 {
     if (SocketState == WebSocketState.Connecting || SocketState == WebSocketState.Closed)
     {
         _socket?.Connect();
     }
 }
Ejemplo n.º 7
0
        public void Play()
        {
            var uri = new Uri(Server + "?user="******"Something strange is happening on the server... Response:\n{0}", response);
                        ShouldExit = true;
                    }
                    else
                    {
                        var boardString = response.Substring(ResponsePrefix.Length);

                        var action = DoMove(new GameBoard(boardString));

                        socket.Send(action);
                    }
                }
            }
        }
Ejemplo n.º 8
0
    void Connect()
    {
        ws =  new WebSocket("ws://socket.nappers.jp:8888");

        // called when websocket messages come.
        ws.OnMessage += (sender, e) =>
        {
            string s = e.Data;
            Debug.Log(string.Format( "Receive {0}",s));
            messages.Add("> " + e.Data);
            if(messages.Count > 10){
                messages.RemoveAt(0);
            }
        };

        ws.OnError += (sender, e) =>
        {
            Debug.Log("OnError");
        };
        ws.OnClose += (sender, e) =>
        {
            Debug.Log("OnClose");

        };
        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("OnOpen");

        };

        ws.Connect();
        Debug.Log("Connect to " + ws.Url);
    }
Ejemplo n.º 9
0
        IEnumerator Start()
        {
            _game = gameObject.GetComponent<MainProxy>();

            _state = ConnectionState.UNKNOWN;
            _socket = new WebSocket (new Uri ("ws://188.242.130.83:3000/echo"));
            yield return StartCoroutine (_socket.Connect ());
        }
Ejemplo n.º 10
0
    public void Connect(string playerName, string url)
    {
        PlayerName = playerName;

        if (Socket != null)
            Disconnect();

        Socket = new WebSocket(new Uri(url));
        StartCoroutine(Socket.Connect());
    }
Ejemplo n.º 11
0
 public void Connect(string host, int port)
 {
     if (Client != null)
     {
         throw new ArgumentException("Already called Connect.");
     }
     Client            = new WebSocket($"ws://{host}:{port}{ServicePath}");
     Client.OnMessage += Client_OnMessage;
     Client?.Connect();
 }
Ejemplo n.º 12
0
    public WebtestClient(string port)
    {
        client = new WebSocket(@"ws://127.0.0.1:" + port + "/Simulator");
        client.Connect();

        client.OnError += (sender, e) =>
              Debug.Log("error: " + e.Message.ToString());
        client.OnClose += (sender, e) =>
            Debug.Log("client on closing");
    }
Ejemplo n.º 13
0
    public PongWebSockets(string WebSocketServerAddress)
    {
        //nf = new Notifier();
        ws = new WebSocket(WebSocketServerAddress);

        ws.OnMessage += Ws_OnMessage;
        ws.OnOpen += Ws_OnOpen;
        ws.OnClose += Ws_OnClose;
        ws.OnError += Ws_OnError;
        ws.Connect();
    }
Ejemplo n.º 14
0
    void Connect()
    {
        ws =  new WebSocket("ws://localhost:8888/");

        // called when websocket messages come.
        ws.OnMessage += (sender, e) =>
        {
            /*
            string s = e.Data;
            Debug.Log(string.Format( "Receive {0}",s));
            messages.Add("> " + e.Data);
            if(messages.Count > 10){
                messages.RemoveAt(0);
            }
            */

            var jsonData = MiniJSON.Json.Deserialize(e.Data) as Dictionary<string,object>;
            string message = (string)jsonData["message"];
            if(message == "returnform")
            {
                //get Map Data
            }
            else if(message == "requestcreateform")
            {
                //createMap
            }
            else if(message == "returnscore")
            {
                // rannkinnguitiran
            }
            else if(message == "sendposition")
            {
                //anotherUserPosition
                Debug.Log("a");
            }
            else if(message == "setuserid")
            {
                SetUserID((string)jsonData["userID"]);
            }
            Debug.Log(message);
        };
        ws.OnError += (sender, e) =>
        {
            Debug.Log("aa");
        };
        ws.OnClose += (sender, e) =>
        {
            Debug.Log("Closing...");

        };
        ws.Connect();
        Debug.Log("Connect to " + ws.Url);
    }
Ejemplo n.º 15
0
    // https://github.com/sta/websocket-sharp
    void Start()
    {
        socket = new WebSocket("ws://literature.uncontext.com:80");

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

        socket.Connect();
    }
Ejemplo n.º 16
0
    public void Reconnect(string WebSocketServerAddress)
    {
        ws.Close();
        ws.OnMessage -= Ws_OnMessage;
        ws.OnOpen -= Ws_OnOpen;
        ws.OnClose -= Ws_OnClose;
        ws.OnError -= Ws_OnError;

        ws = new WebSocket(WebSocketServerAddress);
        ws.OnMessage += Ws_OnMessage;
        ws.OnOpen += Ws_OnOpen;
        ws.OnClose += Ws_OnClose;
        ws.OnError += Ws_OnError;
        ws.Connect();
    }
Ejemplo n.º 17
0
        private static void ListenToMtgox()
        {
            var ws = new WebSocket("ws://" + Dns.GetHostAddresses("websocket.mtgox.com").First().ToString() + ":80/mtgox", "*");
            var observableWs = new ObservableWebsocket(ws);

            if (!ws.Connect())
            {
                Console.WriteLine("Not connected");
                Console.ReadLine();
            }
            else
            {
                Console.Clear();
                Connected(observableWs);
                ws.Close();
            }
        }
Ejemplo n.º 18
0
        private void BeginConnect()
        {
            try
            {
                DebugUtil.LogNormal <WsClientWithTimeout>(DebugLocation.Internal, "BeginConnect",
                                                          "Connecting To WS Edge...");

                _connection?.Connect();
                if (_connection?.IsAlive == true)
                {
                    _connected = true;
                }
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
        }
Ejemplo n.º 19
0
    void Connect()
    {
        ws = new WebSocket (WSAddress);

        ws.OnOpen += (sender, e) => {
            //Debug.Log ("WebSocket Open");
        };
        ws.OnMessage += (sender, e) => {
            //Debug.Log ("WebSocket Message Type: " + e.Type + ", Data: " + e.Data);
        };
        ws.OnError += (sender, e) => {
            //Debug.Log ("WebSocket Error Message: " + e.Message);
        };
        ws.OnClose += (sender, e) => {
            //Debug.Log ("WebSocket Close");
        };
        ws.Connect ();
    }
Ejemplo n.º 20
0
 //TODO: Make this async
 void SocketIOHandShake()
 {
     WebRequest wr = WebRequest.Create("http://worldmanager.rutgers.edu:3003/socket.io/1");
     wr.Method = "POST";
     WebResponse res = wr.GetResponse ();
     StreamReader sr = new StreamReader (res.GetResponseStream());
     string responseString = sr.ReadToEnd ();
     sid = responseString.Substring (0, responseString.IndexOf (':'));
     Debug.Log(responseString);
     int heartbeat = Convert.ToInt32(responseString.Substring (responseString.IndexOf (':')+1, 2));
     ws = new WebSocket ("ws://174.129.18.69:3003/socket.io/1/websocket/"+sid);
     ws.OnMessage += (sender, e) => {
         isAlive = true;
         Debug.Log ("Laputa says: " + e.Data);
     };
     ws.OnError += (object sender, WebSocketSharp.ErrorEventArgs e) =>
         Debug.LogError(e.Message);
     ws.Connect ();
     StartCoroutine ("SendHeartbeat", heartbeat);
 }
Ejemplo n.º 21
0
    //network
    public static void ConnectToServer()
    {
        Game.GameState = Game.GameStateType.ConnectedToServer;

        ws = new WebSocket("ws://127.0.0.1:8080", "echo-protocol");		//production: ws://ec2-54-227-104-51.compute-1.amazonaws.com:8080/

        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("connection with server opened");
            if (ServerConnect != null) ServerConnect();
            Loom.QueueOnMainThread(()=>{
                ws.Send( JsonConvert.SerializeObject( new NetworkMsg(){ type = "connectRequest" }) );
            });
        };

        ws.OnMessage += delegate(object sender, MessageEventArgs e) {
            NetworkMsg ms = JsonConvert.DeserializeObject<NetworkMsg>(e.Data);
            //Debug.Log("from: " + ms.id + " type: " +  ms.type + " tata: " + ms.msg);
            if (ServerMsg != null) ServerMsg(ms);
        };

        ws.OnError += delegate(object sender, ErrorEventArgs e) {
            Debug.Log("error: " + e.Message);
            if (ServerError!=null) ServerError();
        };

        ws.OnClose += delegate(object sender, CloseEventArgs e) {
            Debug.Log("connection closed: " + e.Data);
            if (ServerDisonnect!=null) ServerDisonnect();
        };

        ws.OnOpen+= delegate(object sender, System.EventArgs e) {
        };

        #if DEBUG
        ws.Log.Level = LogLevel.TRACE;
        #endif

        ws.Connect();
    }
Ejemplo n.º 22
0
	// Use this for initialization
	IEnumerator Start () {
        WebSocket w = new WebSocket(new Uri("ws://192.168.1.206:8888/ws"));
		yield return StartCoroutine(w.Connect());
		w.SendString("UnityTest");
		int i=0;
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Debug.Log ("Received: "+reply);
                w.SendString("UnityTest " + i++);
			}
			if (w.Error != null)
			{
				Debug.LogError ("Error: "+w.Error);
				break;
			}
			yield return 0;
		}
		w.Close();
	}
    void Connect()
    {
        ws =  new WebSocket("wss://localhost:8888");

        // called when websocket messages come.
        ws.OnMessage += (sender, e) =>
        {
            string s = e.Data;
            //Debug.Log(string.Format( "Receive {0}",s));

            msgQue.Add(e.Data);
        #if false
            messages.Add("> " + e.Data);
            if(messages.Count > 10){
                messages.RemoveAt(0);
            }
        #endif
        };

        ws.Connect();
        Debug.Log("Connect to " + ws.Url);
    }
Ejemplo n.º 24
0
    // Use this for initialization
    void Start()
    {
        var ugly = UnityThreadHelper.Dispatcher;

        wssv = new WebSocketSharp.Server.WebSocketServer ("ws://localhost:7000/");
        wssv.AddWebSocketService<Vis> ("/", () => new Vis () { IgnoreExtensions = true });
        wssv.AddWebSocketService<Laputa> (
            "/Laputa",
            () => new Laputa () {
                IgnoreExtensions = true
            });
        ;
        wssv.Start ();
        Debug.Log ("Is listening: " + wssv.IsListening + " on port " + wssv.Port);

        ws = new WebSocket ("ws://localhost:7000/Laputa");

        ws.OnMessage += (sender, e) =>
            Debug.Log ("Laputa says: " + e.Data);

        ws.Connect ();
    }
Ejemplo n.º 25
0
        public WebSocketEndpoint()
        {
            var websocket = new WebSocket("ws://24.87.140.2:4000/", "basic");

            websocket.OnOpen += (sender, args) =>
                                    {
                                        m_OpenEvent.Set();
                return;
            };
            websocket.OnClose += (sender, args) =>
            {
                return;
            };
            websocket.OnMessage += (sender, args) =>
                                       {
                                           return;
                                       };

            websocket.Connect();

            m_OpenEvent.WaitOne(1000);
            websocket.Send("authenticate a b c");
        }
Ejemplo n.º 26
0
 // Use this for initialization
 IEnumerator Start()
 {
     WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:3000"));
     yield return StartCoroutine(w.Connect());
     w.SendString("Hi there");
     int i = 0;
     while(true)
     {
         string reply = w.RecvString();
         if(reply != null)
         {
             Debug.Log("Received: " + reply);
             w.SendString("Hi there" + i++);
         }
         if(w.Error != null)
         {
             Debug.LogError("Error: " + w.Error);
             break;
         }
         yield return 0;
     }
     w.Close();
 }
Ejemplo n.º 27
0
        IEnumerator Connecting()
        {
            var env = ConstantEnviroment.Instance;
            string uri = env.Network.GetAddress(env.Scene.GetPort(SceneManager.GetActiveScene().name));
            Debug.Log("[Connecting] IP=" + uri + " Group=" + MyPlayerController.Instance.Group);
            var socket = new WebSocket(new Uri(uri));
            yield return StartCoroutine(socket.Connect());

            JsonHash hash = new SyncStatus() { Group = MyPlayerController.Instance.Group, Status = NetworkStatus.Join }.ToHash();
            socket.SendString(Json.Serialize(new JsonList() { hash }));

            while (true)
            {
                yield return null;
                var recv = socket.RecvString();
                Retrieve(recv);
                while(_SynchronizedQueue.Count > 0)
                {
                    Synchronized s = _SynchronizedQueue.Dequeue();
                    SyncStatus status = s as SyncStatus;
                    if (status == null) continue;

                    if (status.Status == NetworkStatus.Accept)
                    {
                        // サーバーと接続できた時
                        Synchronized.MyGroup = status.Group;	// 自分のGroupを登録
                        Synchronized.MyId = status.ShortId;	// 自分のIDを登録
                        MyPlayerController.Instance.SetID(status.Group, status.ShortId);
                        _StartTime = status.Time;	// 始まった時間
                        _WebSocket = socket;	// ソケット登録
                        Debug.Log("[Connected] Group=" + status.Group + " ID=" + Synchronized.MyId + " Time=" + _StartTime);
                        yield break;
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public static void ConnectToWebSocket()
        {
            WebSocket mySocket = new WebSocket();
            mySocket.OpenEvent += new OpenEventHandler((object sender, OpenEventArgs e) =>
            {
                Console.WriteLine("Open Event");
                mySocket.Send("Hello, World");
            });

            mySocket.MessageEvent += new MessageEventHandler((object sender,
            MessageEventArgs e) =>
            {
                Console.WriteLine(e.Data);
            });

            mySocket.CloseEvent += new CloseEventHandler((object sender, CloseEventArgs e) =>
            {
                Console.WriteLine("Close Event");
            });

            mySocket.Connect("ws://localhost:8001/echo");

            //mySocket.Close();
        }
Ejemplo n.º 29
0
	public WsClient () {

		bool success = TestConnection();
		if (success) {
			Debug.Log ("Server check ok");
			string server = String.Format("wss://{0}:{1}/",  ip,  port );
			using (conn = new WebSocket (server,"game"));
			conn.Connect ();

			conn.OnOpen += (sender, e) => conn.Send ("Server Connected");

			conn.OnError += (sender, e) => {
				Debug.Log("Websocket Error");
				conn.Close ();
			};

			conn.OnClose += (sender, e) => {
				Debug.Log("Websocket Close");
				conn.Close ();
			};
		} else {
			Debug.Log ("Server check failed");
			return;
		}

		conn.SslConfiguration.ServerCertificateValidationCallback =
			(sender, certificate, chain, sslPolicyErrors) => {
			// Do something to validate the server certificate.
			Debug.Log ("Cert: " + certificate);

			return true; // If the server certificate is valid.
		};



	}
    public void ConnectToStreamingServer()
    {
        if (MY_TOKEN == string.Empty)
        {
            Debug.LogError("Token cannot be empty when trying to connect to the server.");
            return;
        }

        var wsUrl = string.Format(
            "wss://{0}/model/{1}/predict-rt?token={2}&interim=true&user_id={3}",
            API_BASE,
            MODEL_ID,
            MY_TOKEN,
            "username");

        m_ws = new WebSocket(wsUrl);

        m_ws.OnOpen += (sender, e) =>
        {
            Debug.Log("WebSocket connected");
            m_sttState = STT_State.Stopped;
            UIBinding.OnWSConnected();
        };

        m_ws.OnMessage += (sender, e) => {
            var message = JsonUtility.FromJson <ServerToClientMessage>(e.Data);
            switch (message.type)
            {
            case "ready":
            {
                var streamingStatus = JsonUtility.FromJson <StreamingServerStatus>(e.Data);
                UIBinding.OnConnectionResult(streamingStatus);
            }
            break;

            case "failure":
            {
                var streamingStatus = JsonUtility.FromJson <StreamingServerStatus>(e.Data);
                UIBinding.OnConnectionResult(streamingStatus);
                Debug.LogErrorFormat("Server ({0}) not ready.", streamingStatus.id);
            }
            break;

            case "intent":
            {
                var rtPrediction = JsonUtility.FromJson <RealTimePredictionResult>(e.Data);
                UIBinding.OnReceivedRealtimeResult(rtPrediction);
            }
            break;
            }
        };

        m_ws.OnError += (sender, e) =>
        {
            Debug.LogErrorFormat("WebSocket Error {0}", e.Message);
            UIBinding.OnWSError(e.Message);
        };

        m_ws.OnClose += (sender, e) =>
        {
            Debug.Log("WebSocket Closed");
            UIBinding.OnWSDisconnected();
        };

        m_ws.Connect();
    }
Ejemplo n.º 31
0
 private RconWeb(string connectionString)
 {
     WebSocket = new WebSocket(connectionString);
     WebSocket.Connect();
 }
Ejemplo n.º 32
0
    // Use this for initialization
    IEnumerator Start()
    {
        WebSocket w = new WebSocket(new Uri("ws://178.62.242.126:8000/"));
        yield return StartCoroutine(w.Connect());
        int i=0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                float newAccelerationTarget = parseAcceleration(reply);
                if(newAccelerationTarget > 0.1f){

                    accelerationTargetReached = false;
                    accelerationTarget = 1.0f;
                }

                moveCharacter();
                Debug.Log ("Received: "+reply);
            }
            if (w.Error != null)
            {
                Debug.LogError ("Error: "+w.Error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }
Ejemplo n.º 33
0
 public void Connect(string username)
 {
     _name = username;
     _websocket.Connect();
 }
Ejemplo n.º 34
0
    void Start()
    {
        webSocket = new WebSocket(connectAddress);

        // コネクションを確立したときのハンドラ
        webSocket.OnOpen += (sender, eventArgs) =>
        {
            Debug.Log("WebSocket Opened");
        };

        // エラーが発生したときのハンドラ
        webSocket.OnError += (sender, eventArgs) =>
        {
            Debug.Log("WebSocket Error Message: " + eventArgs.Message);
        };

        // コネクションを閉じたときのハンドラ
        webSocket.OnClose += (sender, eventArgs) =>
        {
            Debug.Log("WebSocket Closed");
        };

        // メッセージを受信したときのハンドラ
        webSocket.OnMessage += (sender, eventArgs) =>
        {
            Debug.Log("WebSocket Message: " + eventArgs.Data);

            var header = JsonUtility.FromJson <RPC.Header>(eventArgs.Data);
            switch (header.Method)
            {
            case "ping":
            {
                var pong = JsonUtility.FromJson <RPC.Ping>(eventArgs.Data);
                Debug.Log(pong.Payload.Message);
                break;
            }

            case "login_response":
            {
                var loginResponse = JsonUtility.FromJson <RPC.LoginResponse>(eventArgs.Data);
                MainThreadExecutor.Enqueue(() => OnLoginResponse(loginResponse.Payload));
                break;
            }

            case "sync":
            {
                var syncMessage = JsonUtility.FromJson <RPC.Sync>(eventArgs.Data);
                MainThreadExecutor.Enqueue(() => OnSync(syncMessage.Payload));
                break;
            }

            case "spawn":
            {
                var spawnResponse = JsonUtility.FromJson <RPC.Spawn>(eventArgs.Data);
                MainThreadExecutor.Enqueue(() => OnSpawn(spawnResponse.Payload));
                break;
            }
            }
        };

        webSocket.Connect();

        Login();
    }
Ejemplo n.º 35
0
 private void Form1_Load(object sender, EventArgs e)
 {
     client            = new WebSocket($"ws://localhost:7777/Dsicord?name={userName}");
     client.OnMessage += Client_OnMessage;
     client.Connect();
 }
Ejemplo n.º 36
0
        public static AjaxCallResult CommitStoryEdit(int storyId, int revisionId, string countryCode, int topicId, string headline, string body, string sources, string comment, int photoId)
        {
            try
            {
                AuthenticationData authData = GetAuthenticationDataAndCulture();

                headline = Uri.UnescapeDataString(headline);

                headline = headline.Trim();
                if (headline.EndsWith("."))
                {
                    headline = headline.TrimEnd('.');
                }
                headline = headline.Replace(" : ", ": ").Replace(" ?", "?").Replace("  ", " ");

                headline = Uri.EscapeDataString(headline);

                if (string.IsNullOrEmpty(countryCode))
                {
                    countryCode = "--";
                }

                string uri = "ws://fwn-internal:15615/Editing?Notify=false&Auth=" +
                             Uri.EscapeDataString(authData.Authority.ToEncryptedXml());
                using (
                    var socketClient =
                        new WebSocket(uri))
                {
                    socketClient.Connect();

                    if (storyId > 0)
                    {
                        Country country = null;
                        if (countryCode != "--")
                        {
                            country = Country.FromCode(countryCode);
                        }

                        Story     story     = Story.FromIdentity(storyId);
                        StoryEdit storyEdit = story.Edit(StoryEditType.Edit, authData.CurrentUser,
                                                         Topic.FromIdentity(topicId), null,
                                                         country, headline, body, sources.Replace("  ", " ").Trim(), comment, photoId);

                        story = Story.FromIdentity(storyId);  // reload

                        string personString = "#" + authData.CurrentUser.Identity.ToString("N0");
                        if (authData.CurrentUser.Identity == story.CreatedByPersonId)
                        {
                            personString = "Author";
                        }

                        JObject storyEditedNotify = new JObject();
                        storyEditedNotify["messageType"]    = "StoryEdited";
                        storyEditedNotify["StoryId"]        = story.Identity;
                        storyEditedNotify["Headline"]       = headline;
                        storyEditedNotify["Body"]           = body;
                        storyEditedNotify["Sources"]        = story.SourceLinksHtml;
                        storyEditedNotify["TopicGeography"] = story.Topic.Name + ", " + story.GeographyName;

                        socketClient.Send(storyEditedNotify.ToString());
                        socketClient.Ping();
                        socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity +
                                          "\",\"StoryEditId\":\"" + storyEdit.Identity +
                                          "\",\"EditType\":\"Edit\",\"Comment\":\"" + comment.Replace("\"", "\\\"") +
                                          "\",\"PersonIdString\":\"" + personString +
                                          "\"}");

                        story.Unlock(authData.CurrentUser);
                    }
                    else
                    {
                        Story story = Story.Create(headline, body, Topic.FromIdentity(topicId),
                                                   (countryCode == "--" ? 1 : -Country.FromCode(countryCode).Identity), sources,
                                                   authData.CurrentUser);
                        if (photoId > 0)
                        {
                            story.Photo = Photo.FromIdentity(photoId);
                        }
                        socketClient.Send("{\"serverRequest\":\"UpdateQueueCounts\"}");
                        socketClient.Ping();
                        socketClient.Send("{\"messageType\":\"StoryCreated\"}");
                    }

                    socketClient.Ping();
                    socketClient.Close();
                }

                return(new AjaxCallResult {
                    Success = true
                });
            }
            catch (Exception exception)
            {
                return(new AjaxCallResult
                {
                    Success = false,
                    DisplayMessage = "An exception was thrown [CommitStoryEdit]:<br/><br/>" + exception.ToString()
                });
            }
        }
Ejemplo n.º 37
0
 private void button1_Click(object sender, EventArgs e)
 {
     ws.Connect().Wait();
     timer1.Enabled = true;
 }
Ejemplo n.º 38
0
        public static void main()
        {
            log.Debug("D2MP starting...");

            ourDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var iconThread = new Thread(delegate()
            {
                using (icon = new ProcessIcon())
                {
                    icon.Display();
                    Application.Run();
                }
            });

            iconThread.SetApartmentState(ApartmentState.STA);
            iconThread.Start();

            try
            {
                var steam    = new SteamFinder();
                var steamDir = steam.FindSteam(true);
                dotaDir = steam.FindDota(true);
                if (steamDir == null || dotaDir == null)
                {
                    log.Fatal("Steam/dota was not found!");
                    return;
                }
                else
                {
                    log.Debug("Steam found: " + steamDir);
                    log.Debug("Dota found: " + dotaDir);
                }

                addonsDir = Path.Combine(dotaDir, "dota/addons/");
                d2mpDir   = Path.Combine(dotaDir, "dota/d2moddin/");
                modDir    = Path.Combine(addonsDir, "d2moddin");
                if (!Directory.Exists(addonsDir))
                {
                    Directory.CreateDirectory(addonsDir);
                }
                if (!Directory.Exists(d2mpDir))
                {
                    Directory.CreateDirectory(d2mpDir);
                }
                if (!Directory.Exists(modDir))
                {
                    Directory.CreateDirectory(modDir);
                }

                {
                    var dirs = Directory.GetDirectories(d2mpDir);
                    modNames = new string[dirs.Length];
                    int i = 0;
                    foreach (var dir in dirs)
                    {
                        var modName = Path.GetFileName(dir);
                        log.Debug("Found mod: " + modName + " detecting version...");
                        var    infoPath    = Path.Combine(d2mpDir, modName + "/addoninfo.txt");
                        string versionFile = "";
                        if (File.Exists(infoPath))
                        {
                            versionFile = File.ReadAllText(infoPath);
                        }
                        var match = Regex.Match(versionFile, @"(addonversion)(\s+)(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)",
                                                RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            string version = match.Groups.Cast <Group>()
                                             .ToList()
                                             .Skip(3)
                                             .Aggregate("", (current, part) => current + part.Value);
                            log.Debug(modName + "=" + version);
                            modNames[i] = modName + "=" + version;
                        }
                        else
                        {
                            log.Error("Can't find version info for mod: " + modName + ", not including");
                            modNames[i] = modName + "=?";
                        }
                        i++;
                    }
                }

                //Detect user
                var           config  = File.ReadAllText(Path.Combine(steamDir, @"config\config.vdf"));
                var           matches = Regex.Matches(config, "\"\\d{17}\"");
                string        steamid;
                List <string> steamids = new List <string>();
                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        steamid = match.Value.Substring(1).Substring(0, match.Value.Length - 2);
                        log.Debug("Steam ID detected: " + steamid);
                        steamids.Add(steamid);
                    }
                }
                else
                {
                    log.Fatal("Could not detect steam ID.");
                    return;
                }

                //Modify gameinfo.txt
                ModGameInfo();

                log.Debug("Starting shutdown file watcher...");
                string pathToShutdownFile = Path.Combine(ourDir, "d2mp.pid");
                File.WriteAllText(pathToShutdownFile, "Delete this file to shutdown D2MP.");

                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path         = ourDir;
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                       | NotifyFilters.FileName;
                watcher.Filter   = "d2mp.pid";
                watcher.Deleted += (sender, args) =>
                {
                    shutDown = true;
                };
                watcher.EnableRaisingEvents = true;

                shutDown = false;
                int tryCount = 0;
                while (tryCount < 30 && !shutDown)
                {
                    using (ws = new WebSocket(server))
                    {
                        ws.OnMessage += (sender, e) =>
                        {
                            log.Debug("server: " + e.Data);
                            if (e.Data == "invalidid")
                            {
                                log.Debug("Invalid ID!");
                                shutDown = true;
                                return;
                            }

                            if (e.Data == "close")
                            {
                                log.Debug("Shutting down due to server request.");
                                shutDown = true;
                                return;
                            }

                            if (e.Data == "uninstall")
                            {
                                log.Debug("Uninstalling due to server request...");
                                Uninstall();
                                shutDown = true;
                                return;
                            }

                            var msgParts = e.Data.Split(':');
                            switch (msgParts[0])
                            {
                            case "installmod":
                                ThreadPool.QueueUserWorkItem(InstallMod, msgParts);
                                break;

                            case "deletemod":
                                ThreadPool.QueueUserWorkItem(DeleteMod, msgParts);
                                break;

                            case "setmod":
                                ThreadPool.QueueUserWorkItem(SetMod, msgParts);
                                break;

                            case "dconnect":
                                ThreadPool.QueueUserWorkItem(ConnectDota, msgParts);
                                break;

                            case "launchdota":
                                ThreadPool.QueueUserWorkItem(LaunchDota, msgParts);
                                break;

                            case "dspectate":
                                ThreadPool.QueueUserWorkItem(SpectateGame, msgParts);
                                break;

                            default:
                                log.Error("Command not recognized: " + msgParts[0]);
                                break;
                            }
                        };

                        ws.OnOpen  += (sender, e) => log.Debug("Connected");
                        ws.OnClose += (sender, args) => log.Debug("Disconnected");
                        ws.Connect();
                        tryCount++;
                        if (!ws.IsAlive)
                        {
                            if (tryCount == 1)
                            {
                                icon.DisplayBubble("Disconnected, attempting to reconnect...");
                            }
                            log.Debug("Can't connect to server, tries: " + tryCount);
                            Thread.Sleep(500);
                            continue;
                        }

                        if (tryCount > 1)
                        {
                            icon.DisplayBubble("Reconnected!");
                        }
                        else
                        {
                            icon.DisplayBubble("Connected and ready to begin installing mods.");
                        }

                        try
                        {
                            var ver =
                                File.ReadAllText(
                                    Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                 "version.txt"));
                            log.Debug("sending version: " + ver);
                            ws.Send("init:" + String.Join(",", steamids.ToArray(), 0, steamids.Count) + ":" + ver +
                                    ":" + String.Join(",", modNames));
                        }
                        catch (Exception ex)
                        {
                            log.Debug("Can't detect ID from version.txt, : " + ex);
                            return;
                        }

                        tryCount = 0;
                        while (ws.IsAlive && !shutDown)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                log.Fatal("Overall error in the program: " + ex);
            }
            UnmodGameInfo();
            Application.Exit();
        }
Ejemplo n.º 39
0
    // Use this for initialization
    void Start()
    {
        CamShell.transform.Rotate(0, 45, 0);
        EnemyShell.transform.Rotate(0, -135, 0);

        player = false;

        // ソケット
        // 家thunderbolt
        //ws = new WebSocket("ws://192.168.10.3:3000");
        // 家wifi
        //ws = new WebSocket("ws://192.168.10.4:3000");
        // 製図
        //ws = new WebSocket("ws://172.21.36.69:3000");
        // 工場2ex
        //ws = new WebSocket("ws://172.28.0.192:3000");
        // 工場2pro
        //ws = new WebSocket("ws://172.28.0.116:3000");

        // startシーンから
        ws = new WebSocket("ws://" + GetAdress.ip + ":3000");

        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("WebSocket Open");
        };

        ws.OnMessage += (sender, e) =>
        {
            Debug.Log(" Data: " + e.Data);

            if (e.Data == "P")
            {
                camSet.transform.position   = new Vector3(-45, 0, -45);
                EnemySet.transform.position = new Vector3(45, 0, 45);
                if (pj == false)
                {
                    player = true;
                    pj     = true;
                }
            }

            if (e.Data == "A0")
            {
                moveX = -2f;
            }
            if (e.Data == "B0")
            {
                moveZ = -2f;
            }
            if (e.Data == "C0")
            {
                moveX = 2f;
            }
            if (e.Data == "D0")
            {
                moveZ = 2f;
            }

            if (e.Data == "A1")
            {
                moveX1 = -2f;
            }
            if (e.Data == "B1")
            {
                moveZ1 = -2f;
            }
            if (e.Data == "C1")
            {
                moveX1 = 2f;
            }
            if (e.Data == "D1")
            {
                moveZ1 = 2f;
            }

            // 回転
            if (e.Data == "L0")
            {
                l0 = true;
            }
            if (e.Data == "R0")
            {
                r0 = true;
            }
            if (e.Data == "L1")
            {
                l1 = true;
            }
            if (e.Data == "R1")
            {
                r1 = true;
            }

            if (e.Data == "M0")
            {
                p0m = true;
            }
            if (e.Data == "M1")
            {
                p1m = true;
            }
        };

        ws.OnError += (sender, e) =>
        {
            Debug.Log("WebSocket could NOT be Opend");

            SceneManager.LoadScene("start");
        };

        ws.Connect();
    }
Ejemplo n.º 40
0
 internal static async Task On_WS_Close(CloseEventArgs args)
 {
     Console.WriteLine("WebSocket Closed");
     await WS.Connect();
 }
Ejemplo n.º 41
0
        public static async Task Start(Session session, CancellationToken cancellationToken)
        {
            await Task.Delay(30000, cancellationToken); //delay running 30s

            ServicePointManager.Expect100Continue = false;

            cancellationToken.ThrowIfCancellationRequested();

            var socketURL = session.LogicSettings.DataSharingDataUrl;

            using (var ws = new WebSocket(socketURL))
            {
                ws.Log.Level  = LogLevel.Fatal;
                ws.Log.Output = (logData, message) =>
                {
                    //silenly, no log exception message to screen that scare people :)
                };

                ws.OnMessage += (sender, e) => { onSocketMessageRecieved(session, sender, e); };

                ws.Connect();
                while (true)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    try
                    {
                        if (retries == 5)
                        {
                            //failed to make connection to server  times contiuing, temporary stop for 10 mins.
                            session.EventDispatcher.Send(new WarnEvent()
                            {
                                Message = "Couldn't establish the connection to necro socket server, Bot will re-connect after 10 mins"
                            });
                            await Task.Delay(1 * 60 * 1000, cancellationToken);

                            retries = 0;
                        }

                        if (events.Count > 0 && ws.ReadyState != WebSocketState.Open)
                        {
                            retries++;
                            ws.Connect();
                        }

                        while (ws.ReadyState == WebSocketState.Open)
                        {
                            //Logger.Write("Connected to necrobot data service.");
                            retries = 0;

                            lock (events)
                            {
                                processing.Clear();
                                processing.AddRange(events);
                            }

                            if (processing.Count > 0 && ws.IsAlive)
                            {
                                if (processing.Count == 1)
                                {
                                    //serialize list will make data bigger, code ugly but save bandwidth and help socket process faster
                                    var data = Serialize(processing.First());
                                    ws.Send($"42[\"pokemon\",{data}]");
                                }
                                else
                                {
                                    var data = Serialize(processing);
                                    ws.Send($"42[\"pokemons\",{data}]");
                                }
                            }
                            lock (events)
                            {
                                events.RemoveAll(x => processing.Any(t => t.EncounterId == x.EncounterId));
                            }
                            await Task.Delay(POLLING_INTERVAL, cancellationToken);

                            ws.Ping();
                        }
                    }
                    catch (IOException)
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = "Disconnect to necro socket. New connection will be established when service available..."
                        });
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        //everytime disconnected with server bot wil reconnect after 15 sec
                        await Task.Delay(POLLING_INTERVAL, cancellationToken);
                    }
                }
            }
        }
Ejemplo n.º 42
0
        public async void Connect()
        {
            string result;

            try
            {
                var response = await RPC.Call <RPC.GetWSAddrParams, string>(options.RpcServerAddr, "getwsaddr", new RPC.GetWSAddrParams(Addr));

                result = response.result;
            }
            catch (Exception e)
            {
                if (!shouldReconnect)
                {
                    return;
                }
                Debug.WriteLine("RPC call failed: " + e);
                Reconnect();
                return;
            }

            try
            {
                var url = "ws://" + result;
                ws = new WebSocket(url);

                ws.OnOpen += (sender, e) =>
                {
                    ws.Send(JsonSerializer.Serialize(new WebSocketRequest("setClient", Addr)));
                    shouldReconnect   = true;
                    reconnectInterval = options.ReconnectIntervalMin;
                };

                ws.OnMessage += (sender, e) =>
                {
                    try
                    {
                        if (e.IsBinary)
                        {
                            HandleMsg(e.RawData);
                            return;
                        }

                        var msg = JsonSerializer.Deserialize <WebSocketResponse>(e.Data);
                        if (msg.Error != WebSocketResponse.ErrCodes.Success)
                        {
                            if (msg.Action.Equals("setClient"))
                            {
                                ws.Close();
                            }

                            return;
                        }

                        switch (msg.Action)
                        {
                        case "setClient":
                            OnConnect?.Invoke();
                            break;

                        case "updateSigChainBlockHash":
                            break;

                        default:
                            Debug.WriteLine("Unknown msg type: " + msg.Action);
                            break;
                        }
                    }
                    catch (Exception t)
                    {
                        Debug.WriteLine(t);
                    }
                };

                ws.OnClose += (sender, e) =>
                {
                    Debug.WriteLine("WebSocket unexpectedly closed: (" + e.Code + ") " + e.Reason);
                    if (!shouldReconnect)
                    {
                        return;
                    }
                    Reconnect();
                };

                ws.OnError += (sender, e) =>
                {
                    Debug.WriteLine(e.Message + ": " + e.Exception);
                };

                ws.Connect();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Create WebSocket failed: " + e);
                if (!shouldReconnect)
                {
                    return;
                }
                Reconnect();
            }
        }
Ejemplo n.º 43
0
 void Connect()
 {
     webSocket            = new WebSocket(Config.SERVER_HOST + ":" + Config.SERVER_PORT);
     webSocket.OnMessage += ParseMessage;
     webSocket.Connect();
 }
Ejemplo n.º 44
0
        public static AjaxCallResult LightStory(int storyId, int revisionId, string lightType, string comment)
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture();

            // TODO: Authorize

            Story story = Story.FromIdentity(storyId);

            try
            {
                // Begin by not confirming GREENLIGHTS unless the RevisionId is correct. Work from there.

                string encryptedAuth = authData.Authority.ToEncryptedXml();
                encryptedAuth = Uri.EscapeDataString(encryptedAuth);

                string uri = "ws://fwn-internal:15615/Editing?Notify=false&Auth=" + encryptedAuth;

                using (
                    var socketClient =
                        new WebSocket(uri))
                {
                    socketClient.Connect();
                    StoryEdit newEdit = null;

                    string personString = "#" + authData.CurrentUser.Identity.ToString("N0");
                    if (authData.CurrentUser.Identity == story.CreatedByPersonId)
                    {
                        personString = "Author";
                    }

                    switch (lightType.ToLowerInvariant())
                    {
                    case "comment":
                        newEdit = story.Edit(StoryEditType.Comment, authData.CurrentUser, comment);
                        socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Comment\",\"Comment\":\"" + comment.Replace("\"", "\\\"") + "\",\"PersonIdString\":\"" + personString + "\"}");

                        break;

                    case "defer":
                        story.Edit(StoryEditType.Defer, authData.CurrentUser);
                        break;

                    case "red":
                        // Ignore revision, just redlight

                        newEdit = story.Edit(StoryEditType.Redlight, authData.CurrentUser, comment);
                        socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Redlight\",\"Comment\":\"" + comment.Replace("\"", "\\\"") + "\",\"PersonIdString\":\"" + personString + "\"}");
                        if (GetStoryApprovalRating(story) < -3)
                        {
                            newEdit = story.Edit(StoryEditType.Rejected, authData.CurrentUser,
                                                 "Below rejection threshold");
                            story.ChangeState(StoryState.Rejected);
                            socketClient.Send("{\"serverRequest\":\"UpdateQueueCounts\"}");
                            socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Rejected\",\"Comment\":\"Below rejection threshold\",\"PersonIdString\":\"" + personString + "\"}");
                            socketClient.Send("{\"messageType\":\"StoryStateChange\",\"StoryId\":\"" + story.Identity + "\",\"StateChange\":\"StoryRejected\"}");
                        }

                        break;

                    case "green":
                        if (story.TopicId == 8)
                        {
                            return(new AjaxCallResult
                            {
                                Success = false,
                                DisplayMessage =
                                    "This is a DRAFT story. It cannot be greenlit until taken out of draft mode. Check for placeholders, then move it to a publication-grade topic before greenlighting."
                            });
                        }

                        if (story.RevisionCount > revisionId)
                        {
                            StoryEdits edits = story.Edits;
                            for (int index = story.RevisionCount; index < edits.Count; index++)
                            {
                                if (edits[index].EditType == StoryEditType.Edit)
                                {
                                    // The story was edited after being sent to client; concurrency error, order reload
                                    return(new AjaxCallResult()
                                    {
                                        Success = false, DisplayMessage = "Reload"
                                    });
                                }
                            }
                        }

                        newEdit = story.Edit(StoryEditType.Greenlight, authData.CurrentUser, comment);
                        socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Greenlight\",\"Comment\":\"\",\"PersonIdString\":\"" + personString + "\"}");
                        if (GetStoryApprovalRating(story) > 2)      // Three people
                        {
                            newEdit = story.Edit(StoryEditType.ToPublishQueue, authData.CurrentUser, "Moved to publication queue");
                            story.ChangeState(StoryState.PublicationQueue);
                            socketClient.Send("{\"serverRequest\":\"UpdateQueueCounts\"}");
                            socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"ToPublishQueue\",\"Comment\":\"Moved to publication queue\",\"PersonIdString\":\"" + personString + "\"}");
                            socketClient.Send("{\"messageType\":\"StoryStateChange\",\"StoryId\":\"" + story.Identity + "\",\"StateChange\":\"ApprovedForPublishing\"}");
                        }

                        break;

                    default:
                        return(new AjaxCallResult
                        {
                            Success = false,
                            DisplayMessage = "Unknown lighting color in call"
                        });
                    }

                    socketClient.Ping(); // causes a small delay
                    socketClient.Close();
                }

                return(new AjaxCallResult {
                    Success = true
                });
            }
            catch (DatabaseConcurrencyException dbException)
            {
                return(new AjaxCallResult {
                    Success = false, DisplayMessage = "Exception thrown:<br/><br/>" + dbException.ToString()
                });
            }
        }
Ejemplo n.º 45
0
        public void Connect()
        {
            if (!isConnected)
            {
                ws         = new WebSocket("ws://" + IPAddress + ":" + Port + "/");
                ws.OnOpen += (sender, e) =>
                {
                    Debug.Log("WebSocket Opened.");
                    isConnected = true;
                };

                ws.OnMessage += (sender, e) =>
                {
                    OperationMessage data = JsonUtility.FromJson <OperationMessage>(e.Data);
                    if (data.op == "publish")
                    {
                        SubscribeMessage msg = JsonUtility.FromJson <SubscribeMessage>(e.Data);
                        foreach (SubscribeManager sm in subscribeManagers)
                        {
                            if (msg.topic == sm.Topic)
                            {
                                if (!sm.IsRunning)
                                {
                                    sm.HandlerFunction(e.Data);
                                }
                            }
                        }
                    }

                    else if (data.op == "service_response")
                    {
                        ServiceResponseMessage msg = JsonUtility.FromJson <ServiceResponseMessage>(e.Data);
                        foreach (ServiceClientManager sc in serviceClientManagers)
                        {
                            if (msg.service == sc.service_name)
                            {
                                sc.ResponseFunction(e.Data);
                            }
                        }
                    }

                    else if (data.op == "call_service")
                    {
                        CallServiceMessage msg = JsonUtility.FromJson <CallServiceMessage>(e.Data);
                        foreach (var ss in serviceServerManagers)
                        {
                            if (msg.service == ss.service)
                            {
                                ss.HandlerFunction(e.Data);
                            }
                        }
                    }
                };

                ws.OnError += (sender, e) =>
                {
                    Debug.Log("WebSocket Error Message: " + e.Message);
                };

                ws.OnClose += (sender, e) =>
                {
                    Debug.Log("WebSocket Closed.");
                    isConnected = false;
                };

                if (IsConnectable())
                {
                    ws.Connect();
                }
            }
        }
Ejemplo n.º 46
0
        // NOTE: All functions in this region are operating in a background thread, do NOT call any Unity functions!
#if !NETFX_CORE
        private void SendMessages()
        {
            try
            {
                WebSocket ws = null;

                ws = new WebSocket(URL);
                if (Headers != null)
                {
                    ws.CustomHeaders = Headers;
                }
                ws.OnOpen    += OnWSOpen;
                ws.OnClose   += OnWSClose;
                ws.OnError   += OnWSError;
                ws.OnMessage += OnWSMessage;

                if (DisableSslVerification)
                {
                    ws.SslConfiguration.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
                    {
                        return(true);
                    };
                }
                else
                {
                    ws.SslConfiguration.ServerCertificateValidationCallback = null;
                }
#if NET_4_6
                //  Enable TLS 1.1 and TLS 1.2 if we are on .NET 4.x
                ws.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.None;
#else
                //  .NET 3.x does not support TLS 1.1 or TLS 1.2
                ws.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls;
#endif
                ws.Connect();

                while (_connectionState == ConnectionState.CONNECTED)
                {
                    _sendEvent.WaitOne(50);

                    Message msg = null;
                    lock (_sendQueue)
                    {
                        if (_sendQueue.Count > 0)
                        {
                            msg = _sendQueue.Dequeue();
                        }
                    }

                    while (msg != null)
                    {
                        if (msg is TextMessage)
                        {
                            ws.Send(((TextMessage)msg).Text);
                        }
                        else if (msg is BinaryMessage)
                        {
                            ws.Send(((BinaryMessage)msg).Data);
                        }

                        msg = null;
                        lock (_sendQueue)
                        {
                            if (_sendQueue.Count > 0)
                            {
                                msg = _sendQueue.Dequeue();
                            }
                        }
                    }
                }

                ws.Close();
            }
            catch (System.Exception e)
            {
                _connectionState = ConnectionState.DISCONNECTED;
                Log.Error("WSConnector", "Caught WebSocket exception: {0}", e.ToString());
            }
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Connects to the WebSocket specified by <see cref="uri"/>, piping in all provided observables, and
        /// returning an observable collection of objects from the endpoint.
        /// </summary>
        /// <param name="uri">
        /// The URI.
        /// </param>
        /// <param name="inputStreams">
        /// The name-value collection of input streams to pipe to the endpoint.
        /// </param>
        /// <param name="serializerSettings">
        /// The serializer Settings.
        /// </param>
        /// <param name="scheduler">The scheduler.</param>
        /// <typeparam name="T">
        /// The underlying type returned by the endpoint.
        /// </typeparam>
        /// <returns>
        /// An observable collection of objects from the endpoint.
        /// </returns>
        public static IObservable <T> Create <T>(
            Uri uri,
            IDictionary <string, IObservable <object> > inputStreams = null,
            JsonSerializerSettings serializerSettings = null,
            IScheduler scheduler = null)
        {
            serializerSettings = serializerSettings ?? JsonConvert.DefaultSettings();
            scheduler          = scheduler ?? new TaskPoolScheduler(Task.Factory);
            return(Observable.Create <T>(
                       incoming =>
            {
                var cancellation = new CancellationTokenSource();
                var exception = default(Exception);
                try
                {
                    // Connect to the WebSocket and pipe all input streams into it.
                    Action <string> onNext = next =>
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            throw new OperationCanceledException("Cancellation requested.");
                        }

                        try
                        {
                            if (string.IsNullOrWhiteSpace(next))
                            {
                                return;
                            }

                            switch (next[0])
                            {
                            case ResponseKind.Next:
                                incoming.OnNext(JsonConvert.DeserializeObject <T>(next.Substring(1), serializerSettings));
                                break;

                            case ResponseKind.Error:
                                var error = next.Substring(1);
                                exception = new WebStreamException(error);
                                cancellation.Cancel();
                                break;

                            case ResponseKind.Completed:
                                cancellation.Cancel();
                                break;

                            case ResponseKind.Final:
                                incoming.OnNext(JsonConvert.DeserializeObject <T>(next.Substring(1), serializerSettings));
                                cancellation.Cancel();
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            exception = new WebStreamException("OnNext failed.", e);
                            cancellation.Cancel();
                        }
                    };
                    Action <Exception> onError = e =>
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            throw new OperationCanceledException("Cancellation requested.");
                        }

                        exception = e;
                        cancellation.Cancel();
                    };
                    Action onClosed = () =>
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            throw new OperationCanceledException("Cancellation requested.");
                        }

                        cancellation.Cancel();
                    };

                    var socket = WebSocket.Connect(uri, cancellation.Token);
                    var incomingSubscription = socket.Subscribe(onNext, onError, onClosed);

                    cancellation.Token.Register(
                        () =>
                    {
                        // If we didn't cancel with an error, complete the incoming messages stream.
                        if (exception == null)
                        {
                            if (cancellation.IsCancellationRequested)
                            {
                                incoming.OnError(new OperationCanceledException("Cancellation requested."));
                            }
                            else
                            {
                                incoming.OnCompleted();
                            }
                        }
                        else
                        {
                            incoming.OnError(exception);
                        }

                        incomingSubscription.Dispose();
                    });

                    // Connect to the socket and subscribe to the 'outgoing' observable while the connection remains opened.
                    SerializeOutgoingMessages(inputStreams, socket, serializerSettings, cancellation.Token, scheduler);
                }
                catch (Exception e)
                {
                    exception = e;
                    cancellation.Cancel();
                    throw;
                }

                // Return a disposable which will unwind everything.
                return Disposable.Create(cancellation.Cancel);
            }).ObserveOn(scheduler).SubscribeOn(scheduler));
        }
Ejemplo n.º 48
0
 // Connects to the websocket
 async public void FindMatch()
 {
     // waiting for messages
     await _websocket.Connect();
 }
Ejemplo n.º 49
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string url     = "";
            bool   connect = false;
            List <Machina.Action> actions = new List <Machina.Action>();
            bool send = false;

            if (!DA.GetData(0, ref url))
            {
                return;
            }
            if (!DA.GetData(1, ref connect))
            {
                return;
            }
            if (!DA.GetDataList(2, actions))
            {
                return;
            }
            if (!DA.GetData(3, ref send))
            {
                return;
            }

            List <string> instructions = new List <string>();

            bool connectedResult;

            if (connect)
            {
                if (_ws == null || !_ws.IsAlive)
                {
                    _ws = new WebSocket(url);
                    _ws.Connect();
                }
                connectedResult = _ws.IsAlive;

                if (!connectedResult)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not connect to Machina Bridge App");
                    return;
                }
            }
            else
            {
                if (_ws != null)
                {
                    _ws.Close();
                }
                connectedResult = _ws.IsAlive;
            }
            DA.SetData(0, connectedResult);

            if (send && connectedResult)
            {
                string ins = "";

                foreach (Machina.Action a in actions)
                {
                    // If attaching a tool, send the tool description first.
                    // This is quick and dirty, a result of this component not taking the robot object as an input.
                    // How coud this be improved...? Should tool creation be an action?
                    if (a.type == Machina.ActionType.Attach)
                    {
                        ActionAttach aa = (ActionAttach)a;
                        ins = aa.tool.ToInstruction();
                        instructions.Add(ins);
                        _ws.Send(ins);
                    }

                    ins = a.ToInstruction();
                    instructions.Add(ins);
                    _ws.Send(ins);
                }
                DA.SetData(1, "Sent!");
            }
            else
            {
                DA.SetData(1, "Nothing sent");
            }

            DA.SetDataList(2, instructions);
        }
Ejemplo n.º 50
0
    void Start()
    {
        svs  = new PlayerController[] { sv1, sv2, sv3, sv4 };
        crs  = new Crystal[] { cr1, cr2, cr3, cr4, cr5, cr6, cr7 };
        d_cr = cr1;
        if (player_No <= 3)
        {
            me = svs[player_No];
            spdImg.SetActive(false);
            atkImg.SetActive(false);
        }
        if (player_No != 0)
        {
            gun.SetActive(false);
        }
        if (player_No != 1)
        {
            chusya.SetActive(false);
        }
        pos = new Vector3(0, 0, 0);
        ws  = new WebSocket("ws://" + ip + ":3000/");

        //接続
        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("WebSocket Open");
        };
        //受信
        ws.OnMessage += (sender, e) =>
        {
            String[] data = e.Data.Split(',');
            //Debug.Log(data[0]);
            if (int.Parse(data[1]) <= 3)//sv
            {
                PlayerController sv = svs[int.Parse(data[1])];
                if (data[0] == "run")
                {
                    Vector3 re_move = new Vector3(float.Parse(data[2]), float.Parse(data[3]), float.Parse(data[4]));
                    sv.re_move = re_move;
                }
                if (data[0] == "stop")
                {
                    sv.stop_pos[0] = float.Parse(data[2]);
                    sv.stop_pos[1] = float.Parse(data[3]);
                    sv.stop_pos[2] = float.Parse(data[4]);
                    sv.stop_check  = true;
                    sv.re_move     = Vector3.zero;
                }
                if (data[0] == "jump")
                {
                    sv.jump_check = true;
                }
                if (data[0] == "decoding")
                {
                    sv.stop_pos[0]  = float.Parse(data[2]);
                    sv.stop_pos[1]  = float.Parse(data[3]);
                    sv.stop_pos[2]  = float.Parse(data[4]);
                    sv.stop_check   = true;
                    sv.decord_check = true;
                }
                if (data[0] == "deco_finish")
                {
                    crs[int.Parse(data[2])].deco_check = true;
                }
                if (data[0] == "therapy")
                {
                    sv.therapy_start = true;
                    sv.thera_check   = true;
                }
                if (data[0] == "thera_stop")
                {
                    sv.thera_check = false;
                }
                if (data[0] == "rescue")
                {
                    sv.res_check = true;
                }
                if (data[0] == "hit")
                {
                    sv.hit_check = false;
                    send_check   = false;
                    if (ht.item == "attack")
                    {
                        sv.hp -= 1;
                    }
                    sv.hp        -= 1;
                    sv.gui_check  = true;
                    ht.doya_check = true;
                }
                if (data[0] == "ju")
                {
                    sv.ju_check = true;
                }
            }
            else
            {//ht
                if (data[0] == "run")
                {
                    Vector3 re_move = new Vector3(float.Parse(data[2]), float.Parse(data[3]), float.Parse(data[4]));
                    ht.re_move = re_move;
                }
                if (data[0] == "stop")
                {
                    ht.stop_pos[0] = float.Parse(data[2]);
                    ht.stop_pos[1] = float.Parse(data[3]);
                    ht.stop_pos[2] = float.Parse(data[4]);
                    ht.stop_check  = true;
                    ht.re_move     = Vector3.zero;
                }
                if (data[0] == "atack")
                {
                    ht.atack_motion = true;
                }
                if (data[0] == "mado")
                {
                    ht.mado_check = true;
                }
                if (data[0] == "saku")
                {
                    ht.saku_check = true;
                }
                if (data[0] == "item")
                {
                    ht.item_id = int.Parse(data[2]);
                }
            }
        };
        //エラー
        ws.OnError += (sender, e) =>
        {
            Debug.Log("WebSocket Error: " + e.Message);
        };
        //通信終了
        ws.OnClose += (sender, e) =>
        {
            Debug.Log("WebSocket Close");
        };

        ws.Connect();
    }
Ejemplo n.º 51
0
 public void Reconnect()
 {
     webSocket.Connect();
 }
Ejemplo n.º 52
0
 void Connect()
 {
     ws = new WebSocket(ipaddress);
     ws.Connect();
 }
Ejemplo n.º 53
0
        public void Init()
        {
            string NonRoutableAddress = "0.0.0.0";
            string LocalHost          = "127.0.0.1";

            #region Setup webserver
            WebSocketServer webSocketServer = new WebSocketServer($"ws://{NonRoutableAddress}:2946");
            webSocketServer.AddWebSocketService <StaticDataServer>("/BSDataPuller/StaticData");
            webSocketServer.AddWebSocketService <LiveDataServer>("/BSDataPuller/LiveData");
            webSocketServer.Start();
            #endregion

            #region Initialize webserver
            using (var ws = new WebSocket($"ws://{LocalHost}:2946/BSDataPuller/StaticData")) { while (!ws.IsAlive)
                                                                                               {
                                                                                                   ws.Connect();
                                                                                               }
                                                                                               ws.Close(); }
            using (var ws = new WebSocket($"ws://{LocalHost}:2946/BSDataPuller/LiveData")) { while (!ws.IsAlive)
                                                                                             {
                                                                                                 ws.Connect();
                                                                                             }
                                                                                             ws.Close(); }
            #endregion
        }
Ejemplo n.º 54
0
    IEnumerator Start()
    {
        // get player
        GameObject player = GameObject.Find("FPSController");

        // connect to server
        WebSocket w = new WebSocket(new Uri("ws://localhost:8000"));

        yield return(StartCoroutine(w.Connect()));

        Debug.Log("CONNECTED TO WEBSOCKETS");

        // generate random ID to have idea for each client (feels unsecure)
        System.Guid myGUID = System.Guid.NewGuid();

        // wait for messages
        while (true)
        {
            // read message
            string message = w.RecvString();
            // check if message is not empty
            if (message != null)
            {
                // Debug.Log("RECEIVED FROM WEBSOCKETS: " + reply);

                // deserialize recieved data
                Players data = JsonUtility.FromJson <Players>(message);

                // if number of players is not enough, create new ones
                if (data.players.Count > otherPlayers.Count)
                {
                    for (int i = 0; i < data.players.Count - otherPlayers.Count; i++)
                    {
                        otherPlayers.Add(Instantiate(otherPlayerObject, data.players[otherPlayers.Count + i].position, Quaternion.identity));
                    }
                }

                // update players positions
                for (int i = 0; i < otherPlayers.Count; i++)
                {
                    // using animation
                    otherPlayers[i].transform.position = Vector3.Lerp(otherPlayers[i].transform.position, data.players[i].position, Time.deltaTime * 10F);
                    // or without animation
                    // otherPlayers[i].transform.position = data.players[i].position;
                }
            }

            // if connection error, break the loop
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }

            // check if player moved
            if (prevPosition != player.transform.position)
            {
                // send update if position had changed
                w.SendString(myGUID + "\t" + player.transform.position.x + "\t" + player.transform.position.y + "\t" + player.transform.position.z);
                prevPosition = player.transform.position;
            }

            yield return(0);
        }

        // if error, close connection
        w.Close();
    }
Ejemplo n.º 55
0
    public async void StartWebSocket()
    {
        WebSocket = new WebSocket("ws://cops-and-robert-server.herokuapp.com/ws/" + roomId);

        WebSocket.OnOpen += () =>
        {
            Debug.Log("Connection open!");
        };

        WebSocket.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
        };

        WebSocket.OnClose += (e) =>
        {
            Debug.Log("Connection closed!");
            Token         = null;
            comms.enabled = false;
            locationPanel.SetActive(false);
            menuPanel.SetActive(true);
            Destroy(player);
            Destroy(Camera.main.gameObject);
        };

        WebSocket.OnMessage += (bytes) =>
        {
            string json = System.Text.Encoding.UTF8.GetString(bytes);
            // Debug.Log(json);
            // foreach (string json in jsonHolder.Replace("\n", string.Empty).Replace("\r", string.Empty).Replace("}{", "}|{").Split('|'))
            // foreach (string json in Regex.Replace(jsonHolder, "/(\r\n)|\n|\r/gm", "|").Split('|'))
            // foreach (string json in jsonHolder.Split('|'))
            // {
            if (!json.Contains("Data"))
            {
                PlayerPacket packet = JsonConvert.DeserializeObject <PlayerPacket>(json);
                if (packet.Token.Equals(Token))
                {
                    return;
                }
                if (Token == null)
                {
                    Token    = packet.Token;
                    IsServer = packet.IsServer;
                    // username = packet.Username;
                    SpawnPlayer();
                }
                else
                {
                    if (otherPlayers.TryGetValue(packet.Token, out OtherController oc))
                    {
                        oc.UpdateTransform(packet);
                    }
                    else
                    {
                        GameObject obj = Instantiate(prefabOtherPlayer, new Vector3(packet.PosX, packet.PosY, packet.PosZ), Quaternion.Euler(packet.RotX, packet.RotY, packet.RotZ));
                        // obj.name = packet.Token;
                        obj.GetComponent <VoiceController>().StartVoice(packet.Token);
                        otherPlayers.Add(packet.Token, obj.GetComponent <OtherController>());
                    }
                }
            }
            else
            {
                VoicePacket packet = JsonConvert.DeserializeObject <VoicePacket>(json);
                if (packet.IsServer)
                {
                    ServerToken = packet.Token;
                }
                if (IsServer && !packet.IsServer && !packet.IsP2P)
                {
                    Debug.Log("SERVER: " + packet.Token + " - " + packet.IsServer + " - " + packet.IsP2P + " - " + comms.IsNetworkInitialized);
                    voiceHolderServer.Add(packet);
                }
                else if (packet.IsServer || packet.IsP2P)
                {
                    Debug.Log("CLIENT: " + packet.Token + " - " + packet.IsServer + " - " + packet.IsP2P + " - " + comms.IsNetworkInitialized);
                    voiceHolderClient.Add(packet);
                }
                else
                {
                    Debug.Log("Unknown voice packet");
                }
            }
            // }
        };

        await WebSocket.Connect();
    }
    public IEnumerator ConnectToWebSocket_InThread(string controllerName)
    {
        Debug.Log("Connection to WebSocket"); //Show received message from server
        //websocketConnection = new WebSocket(new Uri("ws://" + IPAdress + ":" + PortNumber + ControllerName));
        websocketConnection = new WebSocket(new Uri("ws://" + IPAdress + ":" + PortNumber + controllerName));

        yield return StartCoroutine(websocketConnection.Connect());
        SendPackageToServer("CheckConnection");
        //StartCoroutine();

        while (true)
        {
            string answerMessage = websocketConnection.RecvString();
            if (answerMessage != null)
            {
                yield return StartCoroutine(AnswerParser(answerMessage)); //Debug
            }
            if (websocketConnection.Error != null)
            {
                Debug.Log("Error: " + websocketConnection.Error);
                connectionManager.Callback_ServerConnect(false);
                //DisconnectFromWebSocket();
                //ConnectToWebSocket(ControllerName);
                break;
            }
            yield return 0;
        }
    }
Ejemplo n.º 57
0
 public IEnumerator StartConnect()
 {
     return(web_socket.Connect());
 }
Ejemplo n.º 58
0
        static void Run(IPAddress tvaddr, Int32 tvport, IPAddress controladdr, Int32 controlport)
        {
            string   response = string.Empty;
            bool     res      = false;
            Response resp     = null;

            var tvws = new StringBuilder();

            tvws.Append("ws://");
            tvws.Append(tvaddr.ToString());
            tvws.Append(":");
            tvws.Append(tvport.ToString());
            Console.WriteLine(tvws.ToString());

            using (var ws = new WebSocket(tvws.ToString()))
            {
                try
                {
                    ws.OnMessage += (sender, e) =>
                    {
                        if (e.Data.Contains("netinput.pointer.sock"))
                        {
                            response = e.Data.ToString();
                            res      = true;
                        }
                        else if (e.Data.Contains("client-key"))
                        {
                            ws.Send("{\"type\":\"request\",\"id\":5,\"uri\":\"ssap://com.webos.service.networkinput/getPointerInputSocket\"}");
                        }
                        else if (e.Data.Contains("denied"))
                        {
                            Console.WriteLine("Denied by user");
                            Process.GetCurrentProcess().Kill();
                        }
                    };

                    ws.Connect();

                    Task task = Task.Run(() => { ws.Connect(); });
                    if (!task.Wait(TimeSpan.FromSeconds(5)))
                    {
                        Console.WriteLine("TimeOut: Connect");
                        Process.GetCurrentProcess().Kill();
                    }

                    ws.Send("{\"type\":\"register\",\"id\":1,\"payload\":{\"manifest\":{\"manifestVersion\":1,\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CONTROL_AUDIO\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_POWER\",\"READ_INSTALLED_APPS\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_TV\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\"]}}}");

                    var cancelToken = new CancellationTokenSource();
                    Task.Factory.StartNew(() => timeout(), cancelToken.Token);

                    while (ws.IsAlive && !res)
                    {
                        ;
                    }
                    cancelToken.Cancel(false);
                    resp = JsonConvert.DeserializeObject <Response>(response);
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Process.GetCurrentProcess().Kill();
                }
            }

            using (var ws = new WebSocket(resp.payload.socketPath))
            {
                ws.Connect();
                using (var subSocket = new SubscriberSocket())
                {
                    var controlzmq = new StringBuilder();
                    controlzmq.Append("tcp://");
                    controlzmq.Append(controladdr.ToString());
                    controlzmq.Append(":");
                    controlzmq.Append(controlport.ToString());

                    subSocket.Options.ReceiveHighWatermark = 1000;
                    subSocket.Connect(controlzmq.ToString());
                    subSocket.Subscribe("x");

                    float x             = 0.0f;
                    float y             = 0.0f;
                    float multi         = 10.0f;
                    int   square_flag   = 0;
                    int   traingle_flag = 0;

                    while (true)
                    {
                        string messageTopicReceived = subSocket.ReceiveFrameString();
                        Console.WriteLine(messageTopicReceived);
                        string messageReceived = subSocket.ReceiveFrameString();
                        Console.WriteLine(messageReceived);

                        PsMove psmove = JsonConvert.DeserializeObject <PsMove>(messageReceived);
                        var    sb     = new StringBuilder();

                        x = psmove.x;
                        y = psmove.y;

                        if (psmove.circle == 1)
                        {
                            sb = new StringBuilder();

                            sb.Append("type:button\n");
                            sb.Append("name:" + "LEFT" + "\n");
                            sb.Append("\n");

                            ws.Send(sb.ToString());
                            continue;
                        }

                        if (psmove.square == 1 && square_flag == 0)
                        {
                            square_flag = 1;
                            sb.Append("type:button\n");
                            sb.Append("name:HOME\n");
                            sb.Append("\n");
                            ws.Send(sb.ToString());
                        }

                        if (psmove.square == 0 && square_flag == 1)
                        {
                            square_flag = 0;
                        }

                        if (psmove.traingle == 1 && traingle_flag == 0)
                        {
                            traingle_flag = 1;
                            sb.Append("type:click\n");
                            sb.Append("\n");
                            ws.Send(sb.ToString());
                        }

                        if (psmove.traingle == 0 && traingle_flag == 1)
                        {
                            traingle_flag = 0;
                        }

                        sb.Append("type:move\n");
                        sb.Append("dx:" + psmove.z * multi * -1 + "\n");
                        sb.Append("dy:" + psmove.x * multi * -1 + "\n");
                        sb.Append("down:" + "0" + "\n");
                        sb.Append("\n");
                        ws.Send(sb.ToString());
                    }
                }
            }
        }
        public WSMonitorada(Usuario user, ServerConfig config)
        {
            this.User    = user;
            OneSignalApi = new OneSignalAPI(config.OneSignalToken, config.AppServer, config.OneSignalAppId);

            if (!string.IsNullOrEmpty(user.BinanceAPIKey) && !string.IsNullOrEmpty(user.BinanceAPISecret))
            {
                timerKeepAlive.Interval = TimeSpan.FromMinutes(15).TotalMilliseconds;
                timerKeepAlive.Elapsed += (object source, ElapsedEventArgs e) =>
                {
                    BinanceUserDataStream.KeepAlive(user.BinanceAPIKey, user.BinanceAPISecret);
                };
                timerKeepAlive.Start();
                // a cada 3 horas verifica se o cara possui ordem aberta se nao possuir desconecta ele
                closeconnection.Interval = TimeSpan.FromHours(1).TotalMilliseconds;
                closeconnection.Elapsed += (object source, ElapsedEventArgs e) =>
                {
                    using (var _OrdemRepo = new OrdemRepository())
                    {
                        var ordensabertas = _OrdemRepo.OrdemsAbertas(User.Id);
                        if (ordensabertas.Count == 0)
                        {
                            this.Dispose(true);
                        }
                    }
                };
                closeconnection.Start();

                var result = BinanceUserDataStream.GetListenKey(user.BinanceAPIKey, user.BinanceAPISecret);
                if (result.IsSuccessStatusCode)
                {
                    var res       = result.Content.ReadAsStringAsync().Result;
                    var listenKey = (string)JsonConvert.DeserializeObject <dynamic>(res).listenKey;
                    ws = new WebSocket("wss://stream.binance.com:9443/ws/" + listenKey);
                    //ws.Log.Level = LogLevel.Trace;
                    //ws.Log.File = "C:\\LogConexao\\" + user.nome + ".txt";

                    //Para envio de ping
                    ws.EmitOnPing = true;

                    ws.OnOpen += (sender, e) =>
                    {
                    };

                    ws.OnMessage += (sender, e) =>
                    {
                        if (e.IsPing)
                        {
                            ws.Ping();
                            return;
                        }

                        var content    = e.Data;
                        var ws_Payload = JsonConvert.DeserializeObject <dynamic>(content);

                        //if (ws_Payload.e != "outboundAccountInfo")
                        //{
                        //    Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " => Type (" + ws_Payload.e + ") Payloadobjeto => " + ws_Payload);
                        //}

                        using (var _OrdemRepo = new OrdemRepository())
                        {
                            if ((string)ws_Payload.e == "executionReport")
                            {
                                //Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " => Type (ExecutionReport)  => " + (string)ws_Payload.x + " => " + e.Data);

                                //Ordem Executada
                                if ((string)ws_Payload.x == "TRADE" && (string)ws_Payload.X == "FILLED")
                                {
                                    string ordemID = (string)ws_Payload.c;
                                    var    ordem   = _OrdemRepo.EntradaByBinanceOrderID(ordemID);
                                    //tentar passar o id pra inteiro significa q a ordem foi gerada no meu sistema, o sisteman binance gera uma string
                                    #region OrderEntrada
                                    if (ordem != null && ordem.TipoOrdem_Id == 1)
                                    {
                                        Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " => Type (Ordem Entrada Executada) OrdemId => " + ordemID);
                                        using (var _OrderCommision = new OrdemComissionRepository())
                                        {
                                            var Comission = new OrdemComission
                                            {
                                                Order_Id        = ordem.Id,
                                                ComissionAmount = (decimal)ws_Payload.n,
                                                ComissionAsset  = (string)ws_Payload.N,
                                                QtdExecutada    = (decimal)ws_Payload.z,
                                                ValorExecutado  = (decimal)ws_Payload.p
                                            };
                                            _OrderCommision.Add(Comission);

                                            ordem.DataEntrada      = DateTime.UtcNow;
                                            ordem.OrdemStatus_Id   = 3;
                                            ordem.BinanceStatus_Id = 3;
                                            _OrdemRepo.Update(ordem);
                                            _OrdemRepo.AddReference(ordem, "OrdemStatus");
                                            signalContext.Clients.User(user.Id.ToString()).EntradaRealizada(ordem);
                                            string LimitOrderID, StopOrderID;
                                            do
                                            {
                                                LimitOrderID = Helper.GenerateRandomOcoOrderID(10);
                                            } while (_OrdemRepo.IsValidOrderID(LimitOrderID));
                                            do
                                            {
                                                StopOrderID = Helper.GenerateRandomOcoOrderID(10);
                                            } while (_OrdemRepo.IsValidOrderID(StopOrderID));
                                            var     listAssets      = _OrderCommision.GetOrderComissions(ordem.Id);
                                            decimal SaldoQuantidade = Helper.ArredondarQuantidadeVenda(listAssets, ordem);
                                            var     limitLoss       = Helper.OcoStopLimitWithPercent(ordem.Chamada.Symbol_id, ordem.Chamada.PrecoLoss, 0.5m);
                                            var     ocoReturn       = BinanceRestApi.SendSaidaOco(user.BinanceAPIKey.Trim(), user.BinanceAPISecret.Trim(), ordem.Chamada.Symbol.symbol, SaldoQuantidade, ordem.Chamada.PrecoGain, ordem.Chamada.PrecoLoss, limitLoss, LimitOrderID, StopOrderID);
                                            if (ocoReturn.IsSuccessStatusCode)
                                            {
                                                var ocoRes   = ocoReturn.Content.ReadAsStringAsync().Result;
                                                var ocoObj   = JsonConvert.DeserializeObject <dynamic>(ocoRes);
                                                var OcoOrder = new Ordem
                                                {
                                                    DataCadastro     = DateTime.UtcNow,
                                                    Quantidade       = SaldoQuantidade,
                                                    Chamada_Id       = ordem.Chamada_Id,
                                                    Usuario_Id       = user.Id,
                                                    OrdemStatus_Id   = 3,
                                                    TipoOrdem_Id     = 2,
                                                    BinanceStatus_Id = 1,
                                                    StopOrder_ID     = StopOrderID,
                                                    LimitOrder_ID    = LimitOrderID,
                                                    OcoOrderListId   = (string)ocoObj.listClientOrderId,
                                                    MainOrderID      = ordem.Id
                                                };
                                                _OrdemRepo.Add(OcoOrder);
                                                var resOco = ocoReturn.Content.ReadAsStringAsync().Result;
                                                Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " =>  Type (Ordem OCO Criada sucesso) OcoOrderListID => " + OcoOrder.OcoOrderListId);
                                            }
                                            else
                                            {
                                                var BinanceerrorObj = Helper.GetBinanceErrorObj(ocoReturn);
                                                Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " =>  Type (Erro ao Criar Ordem Oco) MainOrderID => " + ordem.Id + " => code => " + BinanceerrorObj.code + " => msg => " + BinanceerrorObj.msg + "/" + BinanceerrorObj.motivo);
                                            }
                                        }
                                    }
                                    #endregion
                                    #region VendaMercado
                                    else if (ordem != null && ordem.TipoOrdem_Id == 3)
                                    {
                                        var mainorder = _OrdemRepo.GetById((int)ordem.MainOrderID);
                                        mainorder.PrecoVendaMercado = (decimal)ws_Payload.L;
                                        mainorder.OrdemStatus_Id    = 2;
                                        _OrdemRepo.Update(mainorder);
                                    }
                                    #endregion
                                    #region Order Oco
                                    else
                                    {
                                        //var OcoOrderId = (string)ws_Payload.c;
                                        ordem = _OrdemRepo.OcoOrderByBinanceOrderID(ordemID);
                                        if (ordem != null)
                                        {
                                            Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " => Type (Ordem OCO Executada) Stop_Or_Limit_ID => " + ordemID);
                                            var valorExecutado = ws_Payload.p;
                                            ordem.BinanceStatus_Id = 3;
                                            //status da order main tem que ser igual status da ultima ordem filha
                                            var mainOrder = _OrdemRepo.GetWith_Chamada_and_Symbol((int)ordem.MainOrderID);
                                            mainOrder.DataExecucao = DateTime.UtcNow;
                                            using (var _EdicaoAceitaRepo = new EdicaoAceitaRepository())
                                            {
                                                var EdicaoAceita = _EdicaoAceitaRepo.AceitouEdicao(user.Id, mainOrder.Chamada_Id);
                                                if (EdicaoAceita == null)
                                                {
                                                    if (valorExecutado >= ordem.Chamada.PrecoGain)
                                                    {
                                                        ordem.OrdemStatus_Id     = 5;
                                                        mainOrder.OrdemStatus_Id = 5;
                                                        _OrdemRepo.Update(mainOrder);
                                                        _OrdemRepo.Update(ordem);
                                                        signalContext.Clients.User(user.Id.ToString()).GainRealizado(mainOrder);
                                                        OneSignalApi.NotificarUsuario(user, mainOrder.Chamada.Symbol.symbol, NotificationType.Gain);
                                                    }
                                                    else if (valorExecutado <= ordem.Chamada.PrecoLoss)
                                                    {
                                                        ordem.OrdemStatus_Id     = 6;
                                                        mainOrder.OrdemStatus_Id = 6;
                                                        _OrdemRepo.Update(mainOrder);
                                                        _OrdemRepo.Update(ordem);
                                                        signalContext.Clients.User(user.Id.ToString()).LossRealizado(mainOrder);
                                                        OneSignalApi.NotificarUsuario(user, mainOrder.Chamada.Symbol.symbol, NotificationType.Loss);
                                                    }
                                                }
                                                else
                                                {
                                                    if (valorExecutado >= EdicaoAceita.ChamadaEditada.NewGain)
                                                    {
                                                        ordem.OrdemStatus_Id     = 5;
                                                        mainOrder.OrdemStatus_Id = 5;
                                                        _OrdemRepo.Update(mainOrder);
                                                        _OrdemRepo.Update(ordem);
                                                        signalContext.Clients.User(user.Id.ToString()).GainRealizado(mainOrder);
                                                        OneSignalApi.NotificarUsuario(user, mainOrder.Chamada.Symbol.symbol, NotificationType.Gain);
                                                    }
                                                    else if (valorExecutado <= EdicaoAceita.ChamadaEditada.NewLoss)
                                                    {
                                                        ordem.OrdemStatus_Id     = 6;
                                                        mainOrder.OrdemStatus_Id = 6;
                                                        _OrdemRepo.Update(mainOrder);
                                                        _OrdemRepo.Update(ordem);
                                                        signalContext.Clients.User(user.Id.ToString()).LossRealizado(mainOrder);
                                                        OneSignalApi.NotificarUsuario(user, mainOrder.Chamada.Symbol.symbol, NotificationType.Loss);
                                                    }
                                                }
                                            }
                                            signalContext.Clients.User(user.Id.ToString()).RemoverEdicao(ordem.Chamada_Id);
                                        }
                                    }
                                    #endregion
                                }

                                //quando a ordem é quebrada em varios valores
                                else if ((string)ws_Payload.x == "TRADE" && (string)ws_Payload.X == "PARTIALLY_FILLED")
                                {
                                    string ordemID = (string)ws_Payload.c;
                                    var    ordem   = _OrdemRepo.EntradaByBinanceOrderID(ordemID);
                                    if (ordem != null && ordem.TipoOrdem_Id == 1)
                                    {
                                        using (var _OrderCommision = new OrdemComissionRepository())
                                        {
                                            var Comission = new OrdemComission
                                            {
                                                Order_Id        = ordem.Id,
                                                ComissionAmount = (decimal)ws_Payload.n,
                                                ComissionAsset  = (string)ws_Payload.N,
                                                QtdExecutada    = (decimal)ws_Payload.z,
                                                ValorExecutado  = (decimal)ws_Payload.p
                                            };
                                            _OrderCommision.Add(Comission);
                                        }
                                    }
                                }

                                //Ordem Expirada
                                else if ((string)ws_Payload.x == "EXPIRED")
                                {
                                    var orderId = (string)ws_Payload.c;
                                    var ordem   = _OrdemRepo.EntradaByBinanceOrderID(orderId);
                                    if (ordem != null)
                                    {
                                        ordem.DataCancelamento = DateTime.UtcNow;
                                        ordem.BinanceStatus_Id = 7;
                                        ordem.OrdemStatus_Id   = 7;
                                        _OrdemRepo.Update(ordem);
                                        signalContext.Clients.User(user.Id.ToString()).RejeitadaMercadoemFalta(ordem.Id);
                                    }
                                }

                                //Ordem Cancelada
                                else if ((string)ws_Payload.x == "CANCELED")
                                {
                                    var orderId   = (string)ws_Payload.C;
                                    var mainOrder = _OrdemRepo.EntradaByBinanceOrderID(orderId);
                                    if (mainOrder != null && mainOrder.MotivoCancelamento_ID == null)
                                    {
                                        Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " => Type (Ordem Entrada Cancelada) OrderID => " + orderId);
                                        mainOrder.DataCancelamento      = DateTime.UtcNow;
                                        mainOrder.BinanceStatus_Id      = 4;
                                        mainOrder.OrdemStatus_Id        = 4;
                                        mainOrder.MotivoCancelamento_ID = 1;
                                        _OrdemRepo.Update(mainOrder);
                                        signalContext.Clients.User(user.Id.ToString()).OrdemCancelada(mainOrder.MainOrderID == null ? mainOrder.Id : mainOrder.MainOrderID);
                                    }
                                    else
                                    {
                                        Logs.LogOrdem(user.Id + " (" + user.Email + ") => " + DateTime.UtcNow + " => Type (Ordem OCO Cancelada) Stop_Or_Limit_ID => " + orderId);
                                        var Ocoordem = _OrdemRepo.OcoOrderByBinanceOrderID(orderId);
                                        //venda a mercado
                                        if (Ocoordem != null && Ocoordem.MotivoCancelamento_ID == 2)
                                        {
                                            //A principio nao fazer nada
                                        }
                                        //Edicao Aceita
                                        else if (Ocoordem != null && Ocoordem.MotivoCancelamento_ID == 3)
                                        {
                                            //mainOrder = _OrdemRepo.GetById((int)Ocoordem.MainOrderID);
                                            //if (mainOrder != null && mainOrder.OrdemStatus_Id != 4)
                                            //{
                                            //    signalContext.Clients.User(user.Id.ToString()).OrdemCancelada(Ocoordem.MainOrderID == null ? mainOrder.Id : Ocoordem.MainOrderID);
                                            //    mainOrder.OrdemStatus_Id = 4;
                                            //    mainOrder.BinanceStatus_Id = 4;
                                            //    mainOrder.DataCancelamento = DateTime.UtcNow;
                                            //    _OrdemRepo.Update(mainOrder);
                                            //}
                                        }
                                    }
                                }
                            }
                            //Atualiza saldo
                            if ((string)ws_Payload.e == "outboundAccountPosition")
                            {
                                try
                                {
                                    var listAssets = ws_Payload.B.ToObject <List <B> >();
                                    var castedList = (List <B>)listAssets;
                                    var saldoBtc   = castedList.Where(x => x.a == "BTC").FirstOrDefault().f;
                                    signalContext.Clients.User(user.Id.ToString()).AtualizarSaldo(saldoBtc.ToString("N8"));
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    };

                    ws.OnError += (sender, e) =>
                    {
                        Logs.LogConexao(user.Id + " (" + user.Nome + ") => OnError Event => " + DateTime.UtcNow + " Msg Erro => " + e.Message + " => inner exception => " + e.Exception.Message + " => stack trace => " + e.Exception.StackTrace);
                    };

                    ws.OnClose += (sender, e) =>
                    {
                        try
                        {
                            Logs.LogConexao(user.Id + " (" + user.Nome + ") => OnClose Event => " + DateTime.UtcNow + " code => " + e.Code + " motivo => " + e.Reason);
                            var monitor = WSMonitor.Instancia;
                            monitor.RemoveMonitor(User.Id);
                        }
                        catch
                        {
                        }
                    };
                    ws.Connect();
                }
            }
        }
Ejemplo n.º 60
-1
	void Connect(){
		int id = (int)((1.0+Random.value)*0x10000);
		ws =  new WebSocket("ws://localhost:3000/websocket");
		
		// called when websocket messages come.
		ws.OnMessage += (sender, e) =>
		{
			//JSONObjectで解析
			JSONObject json = new JSONObject(e.Data);
			switch(json[0][0].str){
			case "new_message":
				messages.Add(string.Format("> {0}:{1}",json[0][1]["data"]["name"].str,
				                           json[0][1]["data"]["body"].str));
				if(messages.Count > 10){
					messages.RemoveAt(0);
				}
				break;
			case "websocket_rails.ping":
				Debug.Log(string.Format("Send: [\"websocket_rails.pong\",{{\"id\":{0},\"data\":{{}}}}]", id));
				ws.Send(string.Format("[\"websocket_rails.pong\",{{\"id\":{0},\"data\":{{}}}}]", id));
				this.message = "";
				break;
			}
			Debug.Log("Receive: " + e.Data);
		};
		
		ws.Connect();
		Debug.Log("Connect to: " + ws.Url);
	}