// Use this for initialization void Start() { //client.MessageReceived += new MessageReceivedHandler( messageReceive ); client.MessageReceivedQueue += messageReceive; client.eventConnectStatus += delegate(TCPClient.Status status) { Debug.Log("eventConnectStatus: " + status); connectStatus = status.ToString(); }; client.ConnectToServer(); }
private void FixedUpdate() { if (Input.GetKeyDown(KeyCode.Return) && hasAttemptedConnecting) { SendInputMessage(); textField.ActivateInputField(); } else if (Input.GetKeyDown(KeyCode.Return) && !hasAttemptedConnecting) { client.ConnectToServer(textField.text); textField.text = ""; client.chatText[0] = "Connecting to '" + textField.text + "'..."; client.chatText[1] = ""; hasAttemptedConnecting = true; textField.ActivateInputField(); } text.text = ""; for (int i = client.chatText.Length; i > 0;) { text.text += "\n" + client.chatText[--i]; } //foreach (string s in client.chatText) //{ // text.text += "\n" + s; //} //lastLine = client.chatText[0]; }
public void ConnectGameServerResponse(byte[] bytes, IPEndPoint refEp) { ConnectGameServer conv = ConversationFactory.Instance. CreateFromMessage <ConnectGameServer>(bytes, refEp, null, null, null); conv.Start(); ConnectGSMsg convMessage = Message.Decode <ConnectGSMsg>(bytes); //generate TCP client TCPClient client = new TCPClient(); IPEndPoint clientTcp = refEp; clientTcp.Port = convMessage.Port; client.ConnectToServer(clientTcp); int playerId = convMessage.PlayerId; //need to store client tcp somewhere tcpClients.Add(playerId, client); //add player to game Game game; //find game in list if (gameList.Exists(x => x.gameId == convMessage.GameId)) { game = gameList.Find(x => x.gameId == convMessage.GameId); } else { game = new Game(convMessage.GameId, convMessage.Players, SendCard); } game.AddPlayer(playerId); }
public void UdpCommunicator_TestTCPConnect() { TCPClient tc1 = new TCPClient(); TCPClient tc2 = new TCPClient(); IPEndPoint tc1Address = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1027);//IPAddress.Any IPAddress.Parse("127.0.0.1") MessageId msgid = new MessageId() { Pid = 45, Seq = 1 }; Message msg = new Message() { MsgId = msgid, ConvId = msgid, MessageType = TypeOfMessage.Ack }; byte[] msgEnc = msg.Encode(); Message expectedMsgDec = Message.Decode <Message>(msgEnc); tc1.SetupConnection(); Thread.Sleep(1000); tc2.ConnectToServer(tc1Address); tc1.Send(msg.Encode()); Thread.Sleep(100); byte[] msgbytes = tc2.Receive(); Message actualMsgDec = Message.Decode <Message>(msgbytes); Assert.AreEqual(expectedMsgDec.MessageType, actualMsgDec.MessageType); Assert.AreEqual(expectedMsgDec.MsgId, actualMsgDec.MsgId); Assert.AreEqual(expectedMsgDec.ConvId, actualMsgDec.ConvId); }
public void ConnectToServer() { SocketErrorCodes returnCode = tcpClient.ConnectToServer(); if (debug > 0) { CrestronConsole.PrintLine("\n TCPClientClass ConnectToServer returnCode: " + returnCode.ToString()); } if (returnCode == 0) { tcpClient.ReceiveDataAsync(OnDataReceiveEventCallback); } }
public void Send(string ip, int port, string senddata) { try { client.AddressClientConnectedTo = ip; client.PortNumber = port; client.ConnectToServer(); byte[] data = Encoding.GetEncoding(28591).GetBytes(senddata); client.SendData(data, 0, data.Length); client.DisconnectFromServer(); } catch (Exception ex) { ILiveDebug.Instance.WriteLine("ILiveTCPClientSendEx:+" + ex.Message); } }
private void SocketConnect() { SocketErrorCodes s; try { if (Debug) { ErrorLog.Notice("RIO.Driver.OpeningSocket"); } RIO_TcpClient = new TCPClient(RIOEndpoint, 4096); s = RIO_TcpClient.ConnectToServer(); if (Debug) { ErrorLog.Notice("RIO.Driver.Connect: " + s.ToString()); } } catch (SocketException e) { ErrorLog.Error("RIO.Driver SocketException: {0}", e); } }
protected object ConnectionThreadProcess(object o) { var memoryStream = new MemoryStream(); var reader = new StreamReader(memoryStream); var receivedAnything = false; while (true) { var connectCount = 0; while (_remainConnected && !Connected) { connectCount++; _client.AddressClientConnectedTo = _currentAddress; Debug.WriteInfo(GetType().Name, "Address to connect to set to {0}", _currentAddress); var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CloudLog.Notice("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); receivedAnything = false; break; } TryAnotherAddress(); if (connectCount <= 4 || connectCount > 10) { continue; } if (connectCount == 10) { CloudLog.Error("{0} failed to connect to any address, will keep trying in background", GetType().Name); } else { CloudLog.Warn("{0} cannot connect to address: {1}", GetType().Name, _currentAddress); } CrestronEnvironment.AllowOtherAppsToRun(); } _pollTimer = new CTimer(specific => DoNothing(), null, 30000, 30000); _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { Debug.WriteWarn(GetType().Name, "Disconnected!"); _pollTimer.Stop(); _pollTimer.Dispose(); _pollTimer = null; if (_remainConnected) { if (!receivedAnything) { CloudLog.Warn( "{0} connected but didn't receive anything." + "Will wait for 1 minute before reconnection attempt. Upgrade may be in progress.", GetType().Name); Thread.Sleep(60000); } break; } Debug.WriteWarn("Exiting Thread", Thread.CurrentThread.Name); return(null); } receivedAnything = true; #if DEBUG Debug.WriteInfo(GetType().Name, "{0} bytes in buffer", dataCount); #endif for (var i = 0; i < dataCount; i++) { var b = _client.IncomingDataBuffer[i]; if (b != 0) { memoryStream.WriteByte(b); continue; } memoryStream.Position = 0; try { var data = JToken.Parse(reader.ReadToEnd()); memoryStream.SetLength(0); #if DEBUG Debug.WriteInfo(_name + " Rx", Debug.AnsiBlue + data.ToString(Formatting.None) + Debug.AnsiReset); #endif if (data["method"] != null) { OnRequestReceived(this, new QsysRequest(data)); } else if (data["id"] != null) { var id = data["id"].Value <int>(); if (_requests.ContainsKey(id)) { var request = _requests[id]; _requests.Remove(id); OnResponseReceived(this, new QsysResponse(data, request)); } } } catch (Exception e) { CloudLog.Exception("Error occured processing a complete data parcel from Core", e); } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } }
// Methods private void Login(object timer) { if (_Socket.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { _Socket.SocketStatusChange -= SocketStatusHandler; _Socket.DisconnectFromServer(); } SocketErrorCodes err = _Socket.ConnectToServer(); while (_Socket.ClientStatus == SocketStatus.SOCKET_STATUS_WAITING) { Thread.Sleep(100); } if (_Socket.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { ErrorLog.Error("Error connecting to " + this.Name); } _Socket.SocketStatusChange += new TCPClientSocketStatusChangeEventHandler(SocketStatusHandler); string data = ""; int rxlen = 0; // Check for splash screen Thread.Sleep(250); while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } // Check for prompt // Send login if (data.Contains("\r\n> ")) { _SentMessages.TryToDequeue(); SendCmd("login\r\n"); } else // if no prompt, send another line feed { SendCmd("\r\n"); // Check for prompt again Thread.Sleep(250); while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } // On prompt, send login if (data.Contains("\r\n> ")) { _SentMessages.TryToDequeue(); SendCmd("login\r\n"); } } // Check for username prompt: Thread.Sleep(250); data = ""; while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } if (data.Contains("user name:")) // Send the username { _SentMessages.TryToDequeue(); SendCmd("gear7support\r\n"); } // Check for password prompt Thread.Sleep(250); data = ""; while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } if (data.Contains("password:"******"password123!\r\n"); } // Check for success / failure Thread.Sleep(250); data = ""; while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } if (data.Contains("login success")) { _SentMessages.TryToDequeue(); ErrorLog.Notice("Logged in to " + this.Name); GetOutlets(); _PollTimer = new CTimer(new CTimerCallbackFunction(Poll), 30000); return; } else { _SentMessages.TryToDequeue(); ErrorLog.Error("Couldn't log in to " + this.Name); _LoginCount++; if (_LoginCount < 5) { _LoginTimer = new CTimer(new CTimerCallbackFunction(Login), 5000); } return; } }
private object ConnectionThreadProcess(object o) { try { while (true) { var connectCount = 0; while (_remainConnected && !Connected) { if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { Thread.Sleep(5000); continue; } connectCount++; var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CrestronConsole.PrintLine("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); try { OnConnect(); OnStatusChanged(SocketStatusEventType.Connected); } catch (Exception e) { CloudLog.Exception(e); } break; } if (connectCount <= 2 || connectCount > 5) { continue; } if (connectCount == 5) { CloudLog.Error("{0} failed to connect to address: {1}, will keep trying in background", GetType().Name, _client.AddressClientConnectedTo); } CrestronEnvironment.AllowOtherAppsToRun(); } _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { CrestronConsole.PrintLine("{0} Disconnected!", GetType().Name); try { OnStatusChanged(SocketStatusEventType.Disconnected); OnDisconnect(); } catch (Exception e) { CloudLog.Exception(e); } if (_remainConnected) { Thread.Sleep(2000); if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { CloudLog.Warn("{0} Ethernet Link Lost! - sleeping thread until back up", GetType().Name); } break; } CrestronConsole.PrintLine("Exiting {0}", Thread.CurrentThread.Name); return(null); } //CrestronConsole.PrintLine("{0} {1} bytes in buffer", GetType().Name, dataCount); try { OnReceive(_client.IncomingDataBuffer, dataCount); } catch (Exception e) { CloudLog.Exception(e); } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } } catch (Exception e) { if (_remainConnected) { CloudLog.Exception("Error in handler thread while connected / connecting", e); } return(null); } }
public virtual void ConnectToServer() { Client.ConnectToServer(); }
protected object ConnectionThreadProcess(object o) { var index = 0; var bytes = new byte[_client.IncomingDataBuffer.Length]; try { while (true) { var connectCount = 0; while (_remainConnected && !Connected) { connectCount++; var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CloudLog.Notice("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); break; } if (connectCount <= 2 || connectCount > 5) { continue; } if (connectCount == 5) { CloudLog.Error("{0} failed to connect to address: {1}, will keep trying in background", GetType().Name, _client.AddressClientConnectedTo); } else { CloudLog.Warn("{0} cannot connect to address: {1}", GetType().Name, _client.AddressClientConnectedTo); } CrestronEnvironment.AllowOtherAppsToRun(); } _pollTimer = new CTimer(specific => Send("show device status all"), null, 1000, 30000); _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { CloudLog.Debug("{0} Disconnected!", GetType().Name); _pollTimer.Stop(); _pollTimer.Dispose(); if (_remainConnected) { break; } CloudLog.Debug("Exiting {0}", Thread.CurrentThread.Name); return(null); } var promptReceived = false; if (dataCount >= 7) { var lastBytes = new byte[7]; Array.Copy(_client.IncomingDataBuffer, dataCount - 7, lastBytes, 0, 7); var endString = Encoding.UTF8.GetString(lastBytes, 0, lastBytes.Length); if (endString == "Zyper$ ") { promptReceived = true; } } #if DEBUG //CrestronConsole.PrintLine("{0} {1} bytes in buffer, promptReceived = {2}", GetType().Name, dataCount, // promptReceived); //Tools.PrintBytes(_client.IncomingDataBuffer, 0, dataCount, true); #endif for (var i = 0; i < dataCount; i++) { bytes[index] = _client.IncomingDataBuffer[i]; index++; } if (promptReceived) { if (bytes[0] == 0xFF) { #if DEBUG var mode = 0; foreach (var b in bytes) { if (b == 0xFF) { mode = 0; CrestronConsole.Print("ZeeVee Socket Telnet Command Received:"); continue; } if (mode == 0) { switch (b) { case 254: CrestronConsole.Print(" DONT"); break; case 253: CrestronConsole.Print(" DO"); break; case 252: CrestronConsole.Print(" WONT"); break; case 251: CrestronConsole.Print(" WILL"); break; default: CrestronConsole.Print(" {0}", b); break; } mode = 1; continue; } if (mode != 1) { continue; } switch (b) { case 1: CrestronConsole.PrintLine(" Echo"); break; case 3: CrestronConsole.PrintLine(" Suppress Go Ahead"); break; case 5: CrestronConsole.PrintLine(" Status"); break; case 6: CrestronConsole.PrintLine(" Timing Mark"); break; case 24: CrestronConsole.PrintLine(" Terminal Type"); break; case 31: CrestronConsole.PrintLine(" Window Size"); break; case 32: CrestronConsole.PrintLine(" Terminal Speed"); break; case 33: CrestronConsole.PrintLine(" Remote Flow Control"); break; case 34: CrestronConsole.PrintLine(" Linemode"); break; case 36: CrestronConsole.PrintLine(" Environment Variables"); break; default: CrestronConsole.PrintLine(" {0}", b); break; } mode = 2; } #endif index = 0; } else { var data = Encoding.UTF8.GetString(bytes, 0, index - 7); #if DEBUG CrestronConsole.PrintLine("Received response from ZeeVee:\r\n{0}", data); #endif OnReceivedData(this, data); index = 0; } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } } catch (Exception e) { CloudLog.Exception(string.Format("Error in {0}, {1}", Thread.CurrentThread.Name, e.Message), e); CrestronConsole.PrintLine("Error in {0}", Thread.CurrentThread.Name); CrestronConsole.PrintLine("Index = {0}", index); CrestronConsole.Print("Bytes: "); Tools.PrintBytes(bytes, 0, index, true); if (_pollTimer != null && !_pollTimer.Disposed) { _pollTimer.Stop(); _pollTimer.Dispose(); } if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { _client.DisconnectFromServer(); } return(null); } }