public WebSocketService(SignalBus signalBus, MainThreadQueue mainThreadQueue, URLReader urlReader) { Debug.Log("WebSocketService ahoy!"); _signalBus = signalBus; _mainThreadQueue = mainThreadQueue; var browerUri = new UriBuilder(urlReader.ReadURL()); var baseUri = new UriBuilder(WEBSOCKET_PROTOCOL, browerUri.Host, browerUri.Port, browerUri.Path).Uri; var fullUri = new Uri(baseUri, WEBSOCKET_URL_PATH); Debug.Log("Trying to connect to " + fullUri); var url = fullUri.ToString(); //uncomment following line to connect to the deployed server //url = "ws://ggj.sqeezy.tech/socket"; _webSocket = WebSocketFactory.CreateInstance(url); _webSocket.OnOpen += OnOpen; _webSocket.OnMessage += OnMessage; _webSocket.OnError += OnError; _webSocket.OnClose += OnClose; _signalBus.Subscribe <NetworkEvent>(m => Send(m.ToJson())); Connect(); }
public void WSConnect() { // Create WebSocket instance ws = WebSocketFactory.CreateInstance(socket_adress); // Add OnOpen event listener ws.OnOpen += () => { Debug.Log("WS connected!"); Debug.Log("WS state: " + ws.GetState().ToString()); //ws.Send(Encoding.UTF8.GetBytes("Hello from Unity 3D!")); }; // Add OnMessage event listener weOnMessage(); // Add OnError event listener ws.OnError += (string errMsg) => { Debug.Log("WS error: " + errMsg); //ws.Close(); }; // Add OnClose event listener ws.OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); cnntStat = 1; }; // Connect to the server ws.Connect(); }
/// <summary> /// Connects to server then dends XML data /// </summary> public static void Send(XElement body) { if (!_endPointSet) { throw new Exception( "Ip and port wasn't set. Call AccountsTransport.SetIpEndpoint method before sending any data."); } //Create and set up a new socket mySocket = WebSocketFactory.CreateInstance("ws://" + _accountsServerIp + ":" + _accountsServerPort); // buffer message _bufferedMessages.Enqueue(body); // not connected (first message) if (!IsConnected && !IsConnecting) { //Connect(); <- method was removed to make clear meaning of a 'SendBuferedMessages' method and 'IsConnecting' bool IsConnecting = true; //Init callbacks mySocket.OnOpen += SendBuferedMessages; mySocket.OnMessage += OnMessage; mySocket.OnError += OnError; mySocket.OnClose += OnClose; //Connect mySocket.Connect(); } else // if already connected { SendBuferedMessages(); } }
private void RegisterWebSocketEvents() { //Load the settings file from the webserver telling us which server we should be connecting to right now XmlDocument ServerSettingsDocument = new XmlDocument(); ServerSettingsDocument.Load("http://swaelo.com/files/ClientServerSettings.xml"); string UseTestServer = ServerSettingsDocument.DocumentElement.SelectSingleNode("/root/UseTestServer").InnerText; //Load the connection settings file as a text asset, then convert it to an XML document, then read the values from it TextAsset ConnectionsFile = (TextAsset)Resources.Load("ServerConnectionSettings"); XmlDocument ConnectionsDocument = new XmlDocument(); ConnectionsDocument.LoadXml(ConnectionsFile.text); //Load the test and release server IP values from the connection settings resource file string TestServerIP = ConnectionsDocument.DocumentElement.SelectSingleNode("/root/TestServerIP").InnerText; string ReleaseServerIP = ConnectionsDocument.DocumentElement.SelectSingleNode("/root/ReleaseServerIP").InnerText; //Select the IP we were set to use based on the settings file stored on the web server string ServerIP = UseTestServer == "0" ? TestServerIP : ReleaseServerIP; Debug.Log("Connecting to '" + ServerIP + "'"); ServerConnection = WebSocketFactory.CreateInstance(ServerIP); //Register new connection opened event ServerConnection.OnOpen += () => { TryingToConnect = false; ConnectionEstablished = true; }; //Register message received event ServerConnection.OnMessage += (byte[] Message) => { MessageReceived = true; ServerMessage = Message; }; //Register connection error event ServerConnection.OnError += (string Error) => { ConnectionError = true; ErrorMessage = Error; }; //Register connection closed event ServerConnection.OnClose += (WebSocketCloseCode Code) => { ConnectionClosed = true; CloseCode = Code.ToString(); }; }
public void Connect(string url) { if (mSocketClient != null) { throw new Exception("Please disconnect the connected/connecting WebScoket."); } mHost = url; mSocketClient = WebSocketFactory.CreateInstance(url); mSocketClient.OnOpen += OnConnected; mSocketClient.OnClose += OnDisconnected; mSocketClient.OnMessage += OnMessage; mSocketClient.OnError += OnError; mSocketClient.Connect(); }
private void Start() { _wsClient = WebSocketFactory.CreateInstance(ConnectTarget); _wsClient.OnOpen += () => { Debug.Log("Connected GMC server"); }; _wsClient.OnMessage += (byte[] msg) => { Debug.Log($"{System.Text.Encoding.UTF8.GetString(msg)}"); OnGetGmcMessage?.Invoke(msg); }; _wsClient.OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); }; _wsClient.Connect(); }
/// <summary> /// Initialize conenction between game server and client /// </summary> public static void ConnectToGameServer(string ip, int port, string authToken) { if (IsConnectingToGameServer) { Debug.LogWarning("Trying to connect while already connecting. Aborting."); return; } //Observable OnTryingConnectToGameServer(); //Create a connection IsConnectingToGameServer = true; // buffer connection data LastIp = ip; LastPort = port; myToken = authToken; //if player socket exist if (mySocket != null) { //don't do anything if it's already connecter if (IsConnected) { throw new Exception("Error: Trying to connect while already connected."); } throw new Exception("Socket exists but not connected. This should not happen"); //Else if it wasn't connected then destroy connection Disconnect(); return; } //Create and set up a new socket mySocket = WebSocketFactory.CreateInstance("ws://" + ip + ":" + port); //Init callbacks mySocket.OnOpen += OnOpen; mySocket.OnMessage += OnMessage; mySocket.OnError += OnError; mySocket.OnClose += OnClose; // connect mySocket.Connect(); }
// Use this for initialization protected void Start() { // Singelton if (instance != null) { Destroy(this); } if (instance == null) { instance = this; } if (Application.platform != RuntimePlatform.WebGLPlayer) { adress = "ws://joye.dev:9001/"; } adress = adress + target; // Create WebSocket instance Debug.Log("Connecting to " + adress); ws = WebSocketFactory.CreateInstance(adress); // Add OnError event listener ws.OnError += (string errMsg) => { Debug.Log("Chat error: " + errMsg); }; // Add OnClose event listener ws.OnClose += (WebSocketCloseCode code) => { Debug.Log("Chat closed with code: " + code.ToString()); }; // Connect to the server ws.Connect(); StartCoroutine(Ping()); }
public void Initialize() { // Create WebSocket instance // ws = WebSocketFactory.CreateInstance("ws://localhost:9000/echo"); //ws = WebSocketFactory.CreateInstance("ws://localhost:8765"); ws = WebSocketFactory.CreateInstance("ws://135.125.100.181:8765"); // Add OnOpen event listener ws.OnOpen += () => { Debug.Log("WS connected!"); Debug.Log("WS state: " + ws.GetState().ToString()); //ws.Send(Encoding.UTF8.GetBytes("Hello from Unity 3D!")); }; // Add OnMessage event listener ws.OnMessage += (byte[] msg) => { Debug.Log("WS received message: " + Encoding.UTF8.GetString(msg)); // ws.Close(); }; // Add OnError event listener ws.OnError += (string errMsg) => { Debug.Log("WS error: " + errMsg); }; // Add OnClose event listener ws.OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); }; // Connect to the server ws.Connect(); }
// Use this for initialization void Start() { // Create WebSocket instance WebSocket ws = WebSocketFactory.CreateInstance("ws://echo.websocket.org"); // Add OnOpen event listener ws.OnOpen += () => { Debug.Log("WS connected!"); Debug.Log("WS state: " + ws.GetState().ToString()); ws.Send(Encoding.UTF8.GetBytes("Hello from Unity 3D!")); }; // Add OnMessage event listener ws.OnMessage += (byte[] msg) => { Debug.Log("WS received message: " + Encoding.UTF8.GetString(msg)); ws.Close(); }; // Add OnError event listener ws.OnError += (string errMsg) => { Debug.Log("WS error: " + errMsg); }; // Add OnClose event listener ws.OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); }; // Connect to the server ws.Connect(); }
private void Start() { PacketsReceivedManager.Initialize(); // Create WebSocket instance ws = WebSocketFactory.CreateInstance(string.Format("ws://{0}:{1}", ip, port)); // Add OnOpen event listener ws.OnOpen += () => { Debug.Log("WS connected!"); Debug.Log("WS state: " + ws.GetState().ToString()); }; // Add OnMessage event listener ws.OnMessage += (byte[] msg) => { PacketsReceivedManager.ReceiveData(msg); //ws.Close(); }; // Add OnError event listener ws.OnError += (string errMsg) => { Debug.Log("WS error: " + errMsg); }; // Add OnClose event listener ws.OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); }; // Connect to the server ws.Connect(); }
public void InitiateWebSocket(string[] gameServerURL) { // Create WebSocket instance int i = -1; foreach (string url in gameServerURL) { i += 1; if (ws[i] == null || ws[i].GetState().ToString() != "Open") // If not connected { if (ws[i] == null || ws[i].GetState().ToString() != "Connecting") { ws[i] = WebSocketFactory.CreateInstance(url); // Add OnOpen event listener ws[i].OnOpen += () => { Debug.Log("WebSocket connected! Executing your code now..."); }; // Add OnMessage event listener ws[i].OnMessage += (byte[] msg) => { // Handle binary messages from game server try { string str = Encoding.UTF8.GetString(msg); //Debug.Log("WS received message: " + str); // Parse data string into json data structure actionData[i] = ParseResponse(str); if (actionData[i].logs.Length > 0 && i == playerOne) // Is player 1 (The active user) { #if !UNITY_EDITOR ConsoleLog(String.Join("", actionData[i].logs)); // Log to react app console #endif #if UNITY_EDITOR Debug.Log(str); // Log to console #endif } // Response has been received. FixedUpdate should resume. if (actionData[i].data != null) { receivedResponses += 1; } } catch (Exception e) { Debug.Log(e); } //ws.Close(); }; // Add OnError event listener ws[i].OnError += (string errMsg) => { //print("WS error: " + errMsg); Debug.Log("WS closed with code: " + errMsg.ToString()); // Set connected flag to false if (currentGameState == "connected" || currentGameState == "finished") { currentGameState = "loading"; gameFrame = 0; robots = null; receivedResponses = 0; playerOne = 0; framesSinceLastResponse = 0; } }; // Add OnClose event listener ws[i].OnClose += (WebSocketCloseCode code) => { Debug.Log("WS closed with code: " + code.ToString()); // Set connected flag to false Debug.Log("Websocket closed"); if (currentGameState == "connected" || currentGameState == "finished") { currentGameState = "loading"; gameFrame = 0; robots = null; receivedResponses = 0; playerOne = 0; framesSinceLastResponse = 0; } }; // Connect websocket ws[i].Connect(); } } } }
public IWebsocket Build(WebsocketConfiguration config) { var socket = WebSocketFactory.CreateInstance(config.uri.AbsoluteUri); return(new WebsocketSharpAdapter(socket, config)); }