public void NotConnected() { var client = new TCPClient (new System.Net.Sockets.TcpClient ()); Assert.IsFalse (client.Connected); Assert.AreEqual (client.Guid.ToString (), client.Name); Assert.AreEqual ("", client.Address); Assert.DoesNotThrow (client.Close); }
public TCPWrapper(TCPClient.TCPClient TheTCPClient,Logger MyLogger) { TheLogger = MyLogger; this.TheTCPClient = TheTCPClient; this.TheTCPClient.GotData += new TCPClient.TCPClient.GotDataEventHandler(GotData); this.TheTCPClient.GotConnected += new TCPClient.TCPClient.GotConnectedEventHandler(GotServerConnected); this.TheTCPClient.GotDisconnected += new TCPClient.TCPClient.GotDisconnectedEventHandler(GotServerDisconnected); }
/// <summary> /// Get information on a particular domain /// </summary> /// <param name="record"></param> /// <returns></returns> public WhoisRecord FillRecord(WhoisRecord record) { record.Server = getServer(record).Server; var tcpClient = new TCPClient(); record.Text = tcpClient.Read(record.Server, 43, record.Domain); return record; }
public void connect(string ip, int port) { network = new TCPClient(ip, port, "GamePW"); network.OnTextRecieved += new TCPClient.TextRecievedEvent(network_OnTextRecieved); network.OnError += new TCPClient.TCPErrorEvent(network_OnError); network.OnConnect += new TCPClient.ConnectedEvent(network_OnConnect); network.TCP_Connect(); }
public static void Main(string[] args) { cli=new TCPClient("127.0.0.1",10000); cli.UserName="******"; cli.DataManager+= new DataManager(MainClass.OnDataReceived); cli.Connect(); do{ }while(!_exit); cli.CloseConnection(); }
public WorldBot() { TCPClientSettings settings = new TCPClientSettings ( ushort.MaxValue, "127.0.0.1", 15051, true ); _tcpClient = new TCPClient(settings); _tcpClient.Connected += TCPConnected; _tcpClient.DataReceived += TCPClientDataReceived; _tcpClient.Disconnected += TCPClientDisconnected; }
public void Equality () { var clientA = new TCPClient (new System.Net.Sockets.TcpClient ()); TCPClient clientA2 = clientA; var clientB = new TCPClient (new System.Net.Sockets.TcpClient ()); Assert.IsTrue (clientA.Equals (clientA)); Assert.IsFalse (clientA.Equals (clientB)); Assert.IsTrue (clientA == clientA2); Assert.IsFalse (clientA == clientB); Assert.IsFalse (clientA != clientA2); Assert.IsTrue (clientA != clientB); }
public void Connect() { switch (type) { case NetworkType.TCP: tcpInstance = new TCPClient(ipAddress, port, new AsyncCallback(ConnectionCallBack)); Debug.Log("create tcp client"); break; default: break; } }
public void DownloadToClient(String server, string remotefilename, string localfilename) { try { TCPClient tcpc = new TCPClient(); Byte[] read = new Byte[1024]; OptionsLoader ol = new OptionsLoader(); int port = 0; if (ol.Port > 0) { port = ol.Port; } else { // The default in case nothing else is set port = 8081; } // Try to connect to the server IPAddress adr = new IPAddress(server); IPEndPoint ep = new IPEndPoint(adr, port); if (tcpc.Connect(ep) == -1) { throw new Exception("Unable to connect to " + server + " on port " + port); } // Get the stream Stream s = tcpc.GetStream(); Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray()); s.Write( b, 0, b.Length ); int bytes; FileStream fs = new FileStream(localfilename, FileMode.OpenOrCreate); BinaryWriter w = new BinaryWriter(fs); // Read the stream and convert it to ASII while( (bytes = s.Read(read, 0, read.Length)) != 0) { w.Write(read, 0, bytes); read = new Byte[1024]; } tcpc.Close(); w.Close(); fs.Close(); } catch(Exception ex) { throw new Exception(ex.ToString()); } }
public static bool CheckServer(string ip) { try { TCPClient client = new TCPClient(ip, 1338); client.Connect(); client.Send("close;"); return true; } catch { return false; } }
private void LnkChangePassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (txtUsername.Text.Trim().Length != 0 && txtPassword.Text.Trim().Length != 0) { string newPassword = Microsoft.VisualBasic.Interaction.InputBox("Digite a senha nova."); if (newPassword.Trim().Length == 0) { return; } TCPClient tcpClient = new TCPClient(); if (!TCPClient.tcpClient.Connected) { if (!tcpClient.connect()) { return; } } string[] commandArgs = { txtUsername.Text.Trim(), txtPassword.Text.Trim(), newPassword.Trim() }; if (!tcpClient.sendCommand("changepw", commandArgs)) { return; } Stream stream = TCPClient.tcpClient.GetStream(); byte[] buffer = new byte[8192]; stream.Read(buffer, 0, buffer.Length); string response = Encoding.UTF8.GetString(buffer); string[] responsePieces = response.Split(';'); if (responsePieces[0] == "OK") { MessageBox.Show(responsePieces[1], "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (responsePieces[0] == "FAIL") { MessageBox.Show(responsePieces[1], "Falha", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Os campos usuário e senha não podem estar vazios", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//===========================[ Data Delete ]=========================// public bool DataDelete(DoneDelegate callback, string key, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("datadel"); quest.Param("key", key); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
//===========================[ Add Friends ]=========================// public bool AddFriends(DoneDelegate callback, HashSet <long> uids, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("addfriends"); quest.Param("friends", uids); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
/// <summary> /// 注册所有模块设备 /// </summary> private void InitConn(string addr, int remoteport, int localport) { try { //初始化Socket tcp = new TCPClient(addr, remoteport, localport); tcp.SocketStatusChange += new TCPClientSocketStatusChangeEventHandler(tcp_SocketStatusChange); //this.Conn(); } catch (Exception e) { ErrorLog.Error("Error in Remoting: {0}", e.Message); } }
// 192.168.1.3 static void Main(string[] args) { IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001); IClient client = new TCPClient(iPEndPoint); while (true) { string request = Console.ReadLine(); client.Send(request); string response = client.Receive(); Console.WriteLine(response); } }
//===========================[ Add Attributes ]=========================// public bool AddAttributes(DoneDelegate callback, Dictionary <string, string> attrs, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("addattrs"); quest.Param("attrs", attrs); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
FTPConnectData CreateConnectData(ServerIPData sid) { FTPConnectData fcd = new FTPConnectData(); Socket s = TCPClient.CreateSocket(true, true); s.ReceiveBufferSize = 65536 * 2; s.ReceiveTimeout = 10000000; fcd.connected = false; fcd.socket = s; fcd.ippoint = new IPEndPoint(IPAddress.Parse(sid.IP), sid.Port); Thread th = new Thread(new ParameterizedThreadStart(ThreadConnect)); th.Start(fcd); return(fcd); }
//===========================[ Kickout ]=========================// public bool Kickout(DoneDelegate callback, string endpoint, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("kickout"); quest.Param("ce", endpoint); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
//===========================[ Remove Device ]=========================// public bool RemoveDevice(DoneDelegate callback, string deviceToken, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("removedevice"); quest.Param("devicetoken", deviceToken); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
//-------------------------------------// // Function | clientDataTX // Description | Called asynchronously by TCP client on send. Sends the next // message in MessageQueue if available. //-------------------------------------// internal static void clientDataTX(TCPClient _cli, int _bytes) { if (MessageQueue.Count > 0) { if (MessageQueue[0] != "") { client.SendDataAsync(Encoding.ASCII.GetBytes(MessageQueue[0]), MessageQueue[0].Length, clientDataTX); } MessageQueue.RemoveAt(0); } else { waitForTx = false; } }
private void processMessage(TCPClient client, string rawCommand) { if (ReportProcessor.IsReportRequest(rawCommand)) { reportProcessor.ProcessReportRequest(client, rawCommand); } else if (Regex.IsMatch(rawCommand, @"^EXECUTE$")) { commandProcessor.ExecuteJob(client, rawCommand); } else if (Regex.IsMatch(rawCommand, @"^QUEUEJOB$")) { commandProcessor.QueueJob(client, rawCommand); } }
//===========================[ Enter Room ]=========================// public bool EnterRoom(DoneDelegate callback, long roomId, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("enterroom"); quest.Param("rid", roomId); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
private bool SetTranslatedLanguage(DoneDelegate callback, string targetLanguage, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(false); } Quest quest = new Quest("setlang"); quest.Param("lang", targetLanguage); return(client.SendQuest(quest, (Answer answer, int errorCode) => { callback(errorCode); }, timeout)); }
public ChatClient() { logger = LoggerFactory.GetLogger <ChatClient>(); client = new TCPClient <StreamPacket>(IPAddress.Parse("192.168.1.168"), 3210); client.OnConnected += Client_OnConnected; client.OnDisconnected += Client_OnDisconnected; client.OnClientError += Client_OnClientError; client.OnPacketReceived += Client_OnPacketReceived; client.OnPacketSent += Client_OnPacketSent; client.OnPingSent += Client_OnPingSent; client.OnPingReceived += Client_OnPingReceived; client.OnPongSent += Client_OnPongSent; client.OnPongReceived += Client_OnPongReceived; }
//===========================[ Get Group Count ]=========================// //-- Action<member_count, errorCode> public bool GetGroupCount(Action <int, int> callback, long groupId, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { if (RTMConfig.triggerCallbackIfAsyncMethodReturnFalse) { ClientEngine.RunTask(() => { callback(0, fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); }); } return(false); } Quest quest = new Quest("getgroupcount"); quest.Param("gid", groupId); bool asyncStarted = client.SendQuest(quest, (Answer answer, int errorCode) => { int memberCount = 0; if (errorCode == fpnn.ErrorCode.FPNN_EC_OK) { try { memberCount = answer.Want <int>("cn"); } catch (Exception) { errorCode = fpnn.ErrorCode.FPNN_EC_CORE_INVALID_PACKAGE; } } callback(memberCount, errorCode); }, timeout); if (!asyncStarted && RTMConfig.triggerCallbackIfAsyncMethodReturnFalse) { ClientEngine.RunTask(() => { callback(0, fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); }); } return(asyncStarted); }
//===========================[ Get Room Count ]=========================// //-- Action<Dictionary<roomId, count>, errorCode> public bool GetRoomMemberCount(Action <Dictionary <long, int>, int> callback, HashSet <long> roomIds, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { if (RTMConfig.triggerCallbackIfAsyncMethodReturnFalse) { ClientEngine.RunTask(() => { callback(null, fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); }); } return(false); } Quest quest = new Quest("getroomcount"); quest.Param("rids", roomIds); bool asyncStarted = client.SendQuest(quest, (Answer answer, int errorCode) => { Dictionary <long, int> counts = null; if (errorCode == fpnn.ErrorCode.FPNN_EC_OK) { try { counts = WantLongIntDictionary(answer, "cn"); } catch (Exception) { errorCode = fpnn.ErrorCode.FPNN_EC_CORE_INVALID_PACKAGE; } } callback(counts, errorCode); }, timeout); if (!asyncStarted && RTMConfig.triggerCallbackIfAsyncMethodReturnFalse) { ClientEngine.RunTask(() => { callback(null, fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); }); } return(asyncStarted); }
//===========================[ Get Online Users ]=========================// //-- Action<online_uids, errorCode> public bool GetOnlineUsers(Action <HashSet <long>, int> callback, HashSet <long> uids, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { if (RTMConfig.triggerCallbackIfAsyncMethodReturnFalse) { ClientEngine.RunTask(() => { callback(null, fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); }); } return(false); } Quest quest = new Quest("getonlineusers"); quest.Param("uids", uids); bool asyncStarted = client.SendQuest(quest, (Answer answer, int errorCode) => { HashSet <long> onlineUids = null; if (errorCode == fpnn.ErrorCode.FPNN_EC_OK) { try { onlineUids = WantLongHashSet(answer, "uids"); } catch (Exception) { errorCode = fpnn.ErrorCode.FPNN_EC_CORE_INVALID_PACKAGE; } } callback(onlineUids, errorCode); }, timeout); if (!asyncStarted && RTMConfig.triggerCallbackIfAsyncMethodReturnFalse) { ClientEngine.RunTask(() => { callback(null, fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); }); } return(asyncStarted); }
private void ProcessOutbound() { while (true) { SocketMessage socketMessage = m_netpackQueue.Pop(); if (socketMessage == null) { break; } switch (socketMessage.Type) { case SocketMessageType.Connect: { ConnectMessage conn = socketMessage as ConnectMessage; TCPClient tcpClient = (TCPClient)m_tcpObjectContainer.Get(conn.TcpObjectId); tcpClient.Connect(conn.IP, conn.Port); } break; case SocketMessageType.Disconnect: { DisconnectMessage conn = socketMessage as DisconnectMessage; TCPObject tcpObject = m_tcpObjectContainer.Get(conn.TcpObjectId); tcpObject.Disconnect(conn.ConnectionId); } break; case SocketMessageType.DATA: { NetworkPacket netpack = socketMessage as NetworkPacket; TCPObject tcpObject = m_tcpObjectContainer.Get(netpack.TcpObjectId); Session session = tcpObject.GetSessionBy(netpack.ConnectionId); if (session != null) { for (int i = 0; i < netpack.Buffers.Count; i++) { session.Write(netpack.Buffers[i]); } } else { LoggerHelper.Info(0, string.Format("Opaque:{0} ConnectionId:{1} ErrorText:{2}", tcpObject.GetOpaque(), netpack.ConnectionId, "Connection disconnected")); } } break; default: break; } } }
private void button2_Click(object sender, EventArgs e) { var tcpAgent = new TCPClient(id: 0); tcpAgent.form = this; string ip = "127.0.0.1"; string ip2 = "127.0.0.1"; string ip3 = "127.0.0.1"; int port1 = 38245; int port2 = 38246; int port3 = 38244; var t2 = Task.Run(() => tcpAgent.RunClient(IPAddress.Parse(ip), port1, 1)); var t1 = Task.Run(() => tcpAgent.RunClient(IPAddress.Parse(ip2), port2, 2)); var t3 = Task.Run(() => tcpAgent.RunClient(IPAddress.Parse(ip3), port3, 3)); }
private int SetTranslatedLanguage(string targetLanguage, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); } Quest quest = new Quest("setlang"); quest.Param("lang", targetLanguage); Answer answer = client.SendQuest(quest, timeout); return(answer.ErrorCode()); }
public int Kickout(string endpoint, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); } Quest quest = new Quest("kickout"); quest.Param("ce", endpoint); Answer answer = client.SendQuest(quest, timeout); return(answer.ErrorCode()); }
static void DemoSendEmptyQuest(TCPClient client) { Quest quest = new Quest("two way demo"); Answer answer = client.SendQuest(quest); if (answer.IsException()) { ShowErrorAnswer(answer); return; } string v1 = (string)answer.Want("Simple"); int v2 = answer.Want <int>("Simple2"); Debug.Log("Receive answer with 'two way demo' quest: 'Simple':" + v1 + ", 'Simple2':" + v2); }
public void Start() { TCPClient client = new TCPClient(ip, port); Debug.Log("\nBegin demonstration to send one way quest"); DemoSendOneWayQuest(client); Debug.Log("\nBegin demonstration to send empty quest"); DemoSendEmptyQuest(client); Debug.Log("\nBegin demonstration to send quest in synchronous"); DemoSendQuestInSync(client); Debug.Log("\nBegin demonstration to send quest in asynchronous"); DemoSendQuestInAsync(client); }
public async void SetUpTCPConnection() { TCPClient client = new TCPClient(messageService: this); displayMessageStatic("Connection Running"); displayMessageStatic("Sending Messages"); // Send a request to the echo server. string request = "Hello, World!"; await client.Send(request); //await client.Send(request); //await SendLotsOfData(client); }
void Start() { miColi = GetComponent <Collider>(); RigBo = GetComponent <Rigidbody>(); Stop(); if (isServer && !IAPlayer) { myServer = FindObjectOfType <TCPServer>(); } else if (!isServer && !IAPlayer) { myClient = FindObjectOfType <TCPClient>(); } //StartCoroutine(SendMssgs()); }
public int RemoveDevice(string deviceToken, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); } Quest quest = new Quest("removedevice"); quest.Param("devicetoken", deviceToken); Answer answer = client.SendQuest(quest, timeout); return(answer.ErrorCode()); }
public int AddAttributes(Dictionary <string, string> attrs, int timeout = 0) { TCPClient client = GetCoreClient(); if (client == null) { return(fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION); } Quest quest = new Quest("addattrs"); quest.Param("attrs", attrs); Answer answer = client.SendQuest(quest, timeout); return(answer.ErrorCode()); }
// client data received callback method void PJLinkReceiveDataCallback(TCPClient client, int QtyBytesReceived) { if (QtyBytesReceived > 0) { string dataReceived = Encoding.Default.GetString(Client.IncomingDataBuffer, 0, QtyBytesReceived); PJLinkOnDataReceive(dataReceived); client.ReceiveDataAsync(PJLinkReceiveDataCallback); } else { if (client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { Client.ConnectToServerAsync(PJLinkConnectCallBack); // connection dropped, try again! } } }
private void getNewPort(IPAddress managerAddress, int registrationPort) { TCPClient registrationConnection = new TCPClient(managerAddress, registrationPort); SharedLogger.Debug(workerName, "Registration Service", $"Registration sent to {managerAddress}:{registrationPort}."); registrationConnection.SendObject <string>("REGISTER"); //while (!registrationConnection.MessageIsAvailable()) //{ // Thread.Sleep(500); //} string[] registrationInfo = registrationConnection.ReceiveObject <string>().Split('|'); workerName = registrationInfo[1]; managerMessageProcessor.UpdateRunnerName(workerName); SharedLogger.Msg(workerName, "Registration Service", $"Registered to manager server at {managerAddress.ToString()} with port assignment {registrationInfo[0]}."); assignedPort = Convert.ToInt32(registrationInfo[0]); }
void Awake() { tcpServer.IpAddress = "127.0.0.1"; tcpServer.IpPort = 8888; tcpServer.Start(); tcpServer.OnClientConnected += TcpServer_OnClientConnected; for (int i = 0; i < 3; i++) { TCPClient tCPClient = new TCPClient(); tCPClient.IpAddress = tcpServer.IpAddress; tCPClient.IpPort = tcpServer.IpPort; tCPClient.Start(); tcpClients.Add(tCPClient); } }
/* ==== CONSTRUCTOR ==== */ internal ServiceConnection(TCPClient client, ServiceDirection direction) { Direction = direction; if (direction == ServiceDirection.Out) { Accessable = true; } else { Accessable = false; } Client = client; Client.MessageReceived += Client_MessageReceived; Thread thread = new Thread(WatchServer); thread.Start(); }
public void Equality() { Assert.IsFalse (new TCPClient (null).Equals (new TCPClient (null))); Assert.IsFalse (new TCPClient (null) == new TCPClient (null)); Assert.IsTrue (new TCPClient (null) != new TCPClient (null)); var clientA = new TCPClient (null); TCPClient clientA2 = clientA; var clientB = new TCPClient (null); Assert.IsTrue (clientA.Equals (clientA)); Assert.IsFalse (clientA.Equals (clientB)); Assert.IsTrue (clientA == clientA2); Assert.IsFalse (clientA == clientB); Assert.IsFalse (clientA != clientA2); Assert.IsTrue (clientA != clientB); Assert.IsFalse (clientA.Equals (null)); Assert.IsFalse (clientA == null); Assert.IsTrue (clientA != null); }
public Model() { LoadSettings(); Layout = new Layout(); Layout.PropertyChanged += new PropertyChangedEventHandler(Layout_PropertyChanged); LocomotiveDecoderReferenceCollection = new DecoderReferenceCollection(App.StartupPath + decodersFolder, DecoderType.Locomotive); SoundDecoderReferenceCollection = new DecoderReferenceCollection(App.StartupPath + decodersFolder, DecoderType.Sound); AccessoryDecoderReferenceCollection = new DecoderReferenceCollection(App.StartupPath + decodersFolder, DecoderType.Accessory); dlgOpen.DefaultExt = dlgSave.DefaultExt = "layout"; dlgOpen.Filter = dlgSave.Filter = LanguageDictionary.Current.Translate<string>("LayoutFilesFilter", "Text", "Layout files|*.layout|All files|*.*"); TCPClient = new TCPClient(); TCPClient.Started += new EventHandler(TCPClient_Started); TCPClient.Stopped += new EventHandler(TCPClient_Stopped); TCPClient.Error += new ErrorHandler(TCPClient_Error); TCPClient.ServerDisconnected += TCPClient_ServerDisconnected; TCPClient.NetworkMessageProcessor += new NetworkMessageEventHandler(TCPClient_NetworkMessageProcessor); ServerFinder = new ServerFinder(Options.UDPServerPort, "TyphoonCentralStation"); ServerFinder.ServerFound += new EventHandler(ServerFinder_ServerFound); ServerFinder.ServerLost += new EventHandler(ServerFinder_ServerLost); ServerFinder.Start(); CommandBindings.Add(new CommandBinding(RoutedCommands.NewLayout, NewLayout_Executed, NewLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.OpenLayout, OpenLayout_Executed, OpenLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.SaveLayout, SaveLayout_Executed, SaveLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.SaveAsLayout, SaveAsLayout_Executed, SaveAsLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.PrintLayout, PrintLayout_Executed, PrintLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.EmailLayout, EmailLayout_Executed, EmailLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.ImportLayout, ImportLayout_Executed, ImportLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.ExportLayout, ExportLayout_Executed, ExportLayout_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.StationPower, Power_Executed, Power_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.StationRailcom, Railcom_Executed, Railcom_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.AllBrake, AllBrake_Executed, AllBrake_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.AllStop, AllStop_Executed, AllStop_CanExecute)); CommandBindings.Add(new CommandBinding(RoutedCommands.AllReset, AllReset_Executed, AllReset_CanExecute)); }
void receiveBroadcastMessage(IPEndPoint endPoint, string message) { connected = true; dispEndPoint = endPoint; Console.WriteLine(String.Format("Найден диспетчер по адресу {0}. Сообщение от диспетчера: {1}", endPoint.Address.ToString(), message)); try { int port = Convert.ToInt32(ConfigurationManager.AppSettings["dispatcherTCPport"].ToString()); tcpClient = new TCPClient(endPoint.Address.ToString(), port); tcpClient.onMessage += TcpClient_onMessage; tcpClient.onDisconnect += TcpClient_onDisconnect; tcpClient.StartListen(); onFound(); udpClient.Stop(); } catch(SocketException ex) { Console.WriteLine("Не удалось присоединиться к диспетчеру по адресу " + endPoint.Address.ToString() + "ошибка: " + ex.Message); } }
internal void CreateConnection(TCPClient client) { var service = AttatchHandlersToService(new ServiceConnection(client, ServiceConnection.ServiceDirection.In)); Connections.Add(service); }
// to make sure we never get a duplicate of ourselves... kind of a hack :( //private static StoryspaceMainInteraction smi = null; // TODO if we try resetting // TODO use the following if we try resetting to session select page /** * when we awake, make sure there are no duplicates of ourselves * we want only one instance of this class. weird stuff happens with our * TCP communications if we are deleted/recreated or if there are two. * */ /*void Awake() { // is there already this class in existence? if (smi == null) { smi = this; // if not, it'll be us DontDestroyOnLoad(gameObject); // keep us around } else { Destroy(this); // already a class, destroy us and use the other } }*/ /** * Initialize stuff **/ void OnEnable() { Debug.Log("Initializing..."); // disable back button if the initial scene was the "choose current session" // rather than "pick a story!" ?? //GameObject.FindGameObjectWithTag(Constants.TAG_RESET).SetActive(false); // TODO // subscribe to the default global tap/down gesture events FingerGestures.OnFingerTap += HandleFingerGesturesOnFingerTap; FingerGestures.OnFingerDown += HandleFingerGesturesOnFingerDown; // subscribe to the default global drag gesture events FingerGestures.OnDragBegin += FingerGestures_OnDragBegin; FingerGestures.OnDragMove += FingerGestures_OnDragMove; FingerGestures.OnDragEnd += FingerGestures_OnDragEnd; // subscribe to default global two-finger drag gesture events FingerGestures.OnTwoFingerDragBegin += HandleFingerGesturesOnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove += HandleFingerGesturesOnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd += HandleFingerGesturesOnTwoFingerDragEnd; // set up record/playback if (this.recordOn) { this.rap.SetupRecordingFile(); } if (this.loadPlaybacks) { Debug.Log("----------Start loading playbacks----------"); this.rap.LoadAllPlaybackFiles(); Debug.Log("----------Done loading playbacks!----------"); } // set up light this.highlight = GameObject.FindGameObjectWithTag(Constants.TAG_LIGHT); if (this.highlight != null) { this.highlight.SetActive(false); Debug.Log("Got light: " + this.highlight.name); } else { Debug.Log("ERROR: No light found"); } // For testing playback: //StartCoroutine(this.rap.PlaybackFile("playbackfilename")); // set up tcp client... // note: does not attempt to reconnect if connection fails if (this.clientSocket == null) { this.clientSocket = new TCPClient(); this.clientSocket.run (Constants.TCP_IP); this.clientSocket.receivedMsgEvent += new ReceivedMessageEventHandler(HandleClientSocketReceivedMsgEvent); } }
void LoginWindow_Loaded(object sender, RoutedEventArgs e) { _tcpClient = new TCPClient(this); if(!_tcpClient.Connect(Settings.Default.server,Settings.Default.port)) { MessageBox.Show("Unable to connect to HeroWars lobby server.", "connection error", MessageBoxButton.OK, MessageBoxImage.Error); Application.Current.Shutdown(-1); } _tcpClient.Run(); }
public PacketHandler(TCPClient tcpClient, LoginWindow loginWindow) { _tcpClient = tcpClient; _gui = loginWindow; }
private void GotData(object Sender, TCPClient.TCPClient.GotDataEventArgs e) { byte[] b = e.DataBuffer; OnGotCommand(new GotCommandEventArgs(e.DataBuffer)); }
private void InitializeEnvironment() { _map = new ClientMap(); _syncScroll = new object(); _fpsCounterData = new byte[10]; _fpsFontBrush = new SolidBrush(Color.White); _playersData = new Dictionary<int, PlayerDataEx>(); _threadWorld = new Thread(WorldProcessingProc); _threadWorld.IsBackground = true; _threadWorld.Start(); _threadObjectChanged = new Thread(ObjectChangedProc); _threadObjectChanged.IsBackground = true; _threadObjectChanged.Start(); TCPClientSettings settings = new TCPClientSettings ( ushort.MaxValue, "127.0.0.1", 15051, true ); _tcpClient = new TCPClient(settings); _tcpClient.Connected += TCPConnected; _tcpClient.DataReceived += TCPDataReceived; _tcpClient.Disconnected += TCPDisconnected; }
/////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes the Client object /// </summary> /// <param name="host">IP address or host name of the remote host</param> /// <param name="port">Port number of the remote host</param> /////////////////////////////////////////////////////////////////////////////////////////// public void Initialize(string host, int port) { mLastTighteningID = 0; mTighteningIDs = new List<UInt32>(); if (mFlags == OpenProtocolFlags.AutoMode) { mClient = new TCPClient<Message>(host, port, ClientFlags.AutoConnect | ClientFlags.AutoKeepAlive); mClient.Disconnected += new EventHandler(mClient_Disconnected); mClient.MessageReceived += new MessageReceivedEventHandler<Message>(mClient_MessageReceived); mKeepAlive = new Message(MessageType.KeepAlive); mClient.SetKeepAlive(mKeepAlive, 5000); mClient.ThreadCallback += new EventHandler(mClient_ThreadCallback); } else { mClient = new TCPClient<Message>(host, port, ClientFlags.None); } mPSet = 0; //Default to 1 mClient.STX = null; mClient.ETX = 0x00; mTorqueEventLock = new object(); mSendLock = new object(); mInitialized = true; }
internal void CreateConnection(string ip) { if (Connections.Any(i => i.Ip == ip)) return; TCPClient client = new TCPClient(ip, 1338); client.Connect(); var service = AttatchHandlersToService(new ServiceConnection(client, ServiceConnection.ServiceDirection.Out)); Connections.Add(service); }