コード例 #1
0
        /// <summary>
        /// Instantiate a new Node object with the connection to the specefied Address
        /// </summary>
        /// <param id="connectionAddress">The connection Address of the node</param>
        public Node(string connectionAddress)
        {
            //setup node
            Address = connectionAddress;
            int port = int.Parse(Config.GetParameter("SERVER_PORT"));

            client = new TCPClient(Address, port);

            //attatch network events
            client.SetDispatchAction(MessageType.UNKOWN, unknowMessageType);
            client.SetDispatchAction(MessageType.EXECUTION_COMPLETE, returnExecution);
            client.SetDispatchAction(MessageType.EXECUTION_DENIED, deniedExecution);
            client.SetDispatchAction(MessageType.ASSEMBLY_TRANSFER_COMPLETE, assemblyLoaded);
            client.SetDispatchAction(MessageType.VERIFICATION_RESPONSE, verificationResponse);

            //connect
            client.Connect();

            //Send first verification.
            verify();

            //start verification timer
            double hvi = Double.Parse(Config.GetParameter("NODE_VERIFY_INTERVAL"));

            pingTimer           = new Timer(hvi * 1000);
            pingTimer.AutoReset = true;
            pingTimer.Elapsed  += new ElapsedEventHandler(pingTimer_Elapsed);
            pingTimer.Start();
        }
コード例 #2
0
        private void ConnectRA()
        {
            TCManager manager = TCManager.Instance;

            if (manager.RAClient != null)
            {
                ((TCPClient)manager.RAClient).Dispose();
            }

            manager.RAClient = new TCPClient(Settings.Default.RAHost, Settings.Default.RAPort);

            TCPClient client = (TCPClient)manager.RAClient;

            try
            {
                client.Connect();
                client.TCConnected       += _raClient_TCConnected;
                client.TCDisconnected    += _raClient_TCDisconnected;
                client.TCMessageReceived += _raClient_TCMessageReceived;
            }
            catch (Exception ex)
            {
                client.Dispose();

                MessageBoxEx.Show(this, "Could not connect to RA! (" + ex.Message + ")", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #3
0
ファイル: TestTCPClient.cs プロジェクト: netc0/netco-dotnet
        void testTCP()
        {
            Debug.Log("测试 TCP Client");

            TCPClient client = new TCPClient();

            client.OnNetworkStateChanged += (state, err) => {
                Debug.Log("TCP 网络状态改变:" + state + err);
            };

            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

            client.Connect(ipAddress, 9000, () => {
                Debug.Log("TCP连接成功");

                client.Request("game.join", "helloTCP".StringToBytes(), (c, r) => {
                    var msg = r.BytesToString();
                    Console.WriteLine("收到:{0}, {1}", c, msg);
                });

                client.Request("game.login", "login".StringToBytes(), (c, r) => {
                    var msg = r.BytesToString();
                    Console.WriteLine("收到:{0}, {1}", c, msg);
                });
            });
        }
コード例 #4
0
        public bool Connect(bool bTcp, string ip, ushort port, uint newip = 0, ushort newport = 0)
        {
            Debug.Log("连接到服务器 IP = " + ip);
            if (tCPClient != null && tCPClient.IsConnected)
            {
                Debug.Log("TCP is connected.");
                return(false);
            }
            INetClient tt;
            bool       bret = true;

            if (bTcp)
            {
                tt   = new TCPClient(this);
                bret = tt.Connect(ip, port);
            }
            else
            {
                tt   = new UDPClient(this);
                bret = tt.Connect(ip, port);
                //tt = new UDPClient(this);
                //bret = tt.Connect(ip, port, newip, newport);
            }

            tCPClient = tt;
            return(bret);
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: MarvinDrude/MNetworkLib
        static void Main(string[] args)
        {
            Logger.AddDefaultConsoleLogging();

            TCPServer server = new TCPServer();

            server.OnMessage += (cl, me) => {
                Logger.Write("TEST", cl.UID + ": " + me.ToStringContent());

                cl.Send(new TCPMessage()
                {
                    Content = Encoding.UTF8.GetBytes("This is a message from the server")
                });
            };

            server.Start();

            TCPClient client = new TCPClient("192.168.2.113", logging: false);

            client.OnHandshake += () => {
                client.Send(new TCPMessage()
                {
                    Content = Encoding.UTF8.GetBytes("This is a test")
                });
            };

            client.OnMessage += (me) => {
                Logger.Write("TEST", "Server: " + me.ToStringContent());
            };

            client.Connect();
        }
コード例 #6
0
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TCPClient client = new TCPClient("127.0.0.1", 54782);

            client.Connect();
            //remoteDesktopClient1.StartStream();
        }
コード例 #7
0
        private void btncnt_Clicked(object sender, EventArgs e)
        {
            t?.Abort();
            switch (btncnt.Text)
            {
            case "Connect":
                client      = new TCPClient(ip.Text, ushort.Parse(port.Text));
                btncnt.Text = "Disconnect";
                smsg.Text   = "";
                try
                {
                    try { client.Connect(); } catch (Exception ex) { smsg.Text = ex.Message; }
                    Thread.Sleep(500);
                    if (client.Connected)
                    {
                        t = new Thread(new ThreadStart(ListenToServer));
                        t.Start();
                    }
                }
                catch { smsg.Text = "Connection Refused!"; btncnt.Text = "Connect"; }
                break;

            case "Disconnect":
                btncnt.Text = "Connect";
                t.Abort();
                client.SendString("ClientDisconnected-ID:" + id);
                client.Disconnect();
                break;
            }
        }
コード例 #8
0
    public bool Connect(bool bTCP, string ip, ushort port, uint newip = 0, ushort newport = 0)
    {
        if (m_TCPClient != null && m_TCPClient.IsConnected)
        {
            LogMgr.Log("TCP is connected.");
            return(false);
        }
        INetClient tt;
        //bTCP = true;
        bool bret;

        if (bTCP)
        {
            tt   = new TCPClient(this);
            bret = tt.Connect(ip, port, newip, newport);
        }
        else
        {
            tt   = new UDPClient(this);
            bret = tt.Connect(ip, port, newip, newport);
        }

        m_TCPClient = tt;
        return(bret);
    }
コード例 #9
0
 public void SendThread(object obj)
 {
     byte[] magic = System.BitConverter.GetBytes(MAGIC_NUMBER);
     while (true)
     {
         try
         {
             if (ServerSetting.ReporterIP != null)
             {
                 if (m_ErrList.HasItem())
                 {
                     string    str = m_ErrList.GetItem();
                     TCPClient tt  = new TCPClient(null);
                     if (tt.Connect(ServerSetting.ReporterIP, ServerSetting.ReporterPort, 0, 0, false))
                     {
                         byte[] txt      = System.Text.Encoding.ASCII.GetBytes(str);
                         byte[] size     = System.BitConverter.GetBytes((ushort)txt.Length);
                         byte[] sendData = new byte[txt.Length + 6];
                         System.Array.Copy(txt, 0, sendData, 6, txt.Length);
                         System.Array.Copy(size, 0, sendData, 4, size.Length);
                         System.Array.Copy(magic, 0, sendData, 0, magic.Length);
                         tt.Send(sendData);
                         tt.Disconnect();
                     }
                 }
             }
         }
         catch
         {
         }
         Thread.Sleep(500);
     }
 }
コード例 #10
0
ファイル: RobotClient.cs プロジェクト: CancerRobot/Robot
        public void Connect(int id, int token, string ip, int port)
        {
            UserID     = id;
            Token      = token;
            UserName   = "******" + id;
            LoadRoleOK = false;
            //进行移动的操作
            gridX       = Rand.Next(1, totalGridXNum);
            gridY       = Rand.Next(1, totalGridYNum);
            CurrentGrid = new Point(gridX, gridY);
            CurrentDir  = (Dircetions)Rand.Next(0, 8);

            _tcpClient = new TCPClient();

            //添加事件处理
            _tcpClient.SocketConnect += SocketConnect;
            try
            {
                //先建立连接
                _tcpClient.Connect(ip, port);
            }
            catch (Exception e)
            {
                MainWindow.GetInstance().ShowText(e.ToString());
            }
            //先关闭连接
            ActiveDisconnect = false;

            GetRoleList();
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: asmrobot/waxbill
        public static void WaxbillSend()
        {
            byte[]    datas  = new byte[1000];
            TCPClient client = new TCPClient(RealtimeProtocol.Define);

            client.OnConnected += new Action <TCPClient, Session>((c, session) => {
                Console.WriteLine("connected");
            });


            client.OnDisconnected += new Action <TCPClient, Session, CloseReason>((c, session, reason) => {
                Console.WriteLine("disconnected:" + reason.ToString());
            });


            client.OnSended += new Action <TCPClient, Session, SendingQueue, Boolean>((c, session, queue, result) => {
                Console.WriteLine("send:" + result.ToString());
            });



            client.OnReceived += new Action <TCPClient, Session, Packet>((c, session, packet) => {
                Console.WriteLine("receive");
            });



            client.Connect("127.0.0.1", 7888);
            while (true)
            {
                client.Send(datas);
                System.Threading.Thread.Sleep(30);
            }
        }
コード例 #12
0
        //This method works by checking whether the book description(passed into the method's arguments) is null or empty. If it is not null or empty then it will check whether contains more than 30 words. If it is then the it will connect to the Python text summariser through TCP and send
        //the book description to it such that it will summarise it and send it back to the client. After is receives it, this method will return this summarised description. If the descriptions contains less than 30 words
        //then the method will return the book description without it being summarised. If the book description(passed into the method's argument) is null or empty then the method will return an empty string.

        //Note- To provide a way for the server to know that the entire book description has been retrieved, the "#" will be used to mark the end of the string
        public string SummariseDescription(string bookDescription)
        {
            TCPClient client = new TCPClient();
            string    summarisedBookDescription = "";

            if (!String.IsNullOrEmpty(bookDescription))
            {
                //Check if description contains more than 30 words
                if (bookDescription.Split(' ').Count() > 30)
                {
                    summarisedBookDescription = client.Connect(bookDescription);
                    while (String.IsNullOrEmpty(summarisedBookDescription))
                    {
                        //Do nothing
                    }
                    return(summarisedBookDescription);
                }
                else
                {
                    return(bookDescription);
                }
            }
            else
            {
                return("");
            }
        }
コード例 #13
0
ファイル: MapControl.cs プロジェクト: PsychoTeras/RatKing
        public void ConnectToHost()
        {
            if (_connecting)
            {
                WriteLog("!ConnectToHost");
                return;
            }
            _connecting = true;

            WriteLog("ConnectToHost");

            try
            {
                lock (_playersData)
                {
                    _playersData.Clear();
                    _playersRo = new ReadOnlyCollection <PlayerDataEx>(new PlayerDataEx[] {});
                }

                DisconnectFromHost();
                _tcpClient.Connect();
            }
            catch (Exception ex)
            {
                string msg = string.Format("ConnectToHost:\r\n{0}", ex);
                MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _connecting = false;
            }
        }
コード例 #14
0
        private void RefreshMasterServerListings()
        {
            masterClient = new TCPMasterClient();

            masterClient.serverAccepted += (sender) =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", Settings.serverId);
                    getData.Add("type", Settings.type);
                    getData.Add("mode", Settings.mode);

                    sendData.Add("get", getData);

                    // Send the request to the server
                    masterClient.Send(TextFrame.CreateFromString(masterClient.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    masterClient.Disconnect(true);
                    masterClient = null;
                }
            };

            masterClient.textMessageReceived += (player, frame, sender) =>
            {
                try
                {
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    if (data["hosts"] != null)
                    {
                        var response = new MasterServerResponse(data["hosts"].AsArray);

                        if (response != null && response.serverResponse.Count > 0)
                        {
                            // Go through all of the available hosts and add them to the server browser
                            foreach (var server in response.serverResponse)
                            {
                                // Run on main thread as we are creating UnityEngine.GameObjects
                                MainThreadManager.Run(() => AddServer(server.Address, server.Port));
                            }
                        }
                    }
                } finally
                {
                    if (masterClient != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        masterClient.Disconnect(true);
                        masterClient = null;
                    }
                }
            };

            masterClient.Connect(Settings.masterServerHost, Settings.masterServerPort);
        }
コード例 #15
0
 public void Connect()
 {
     if (!this.client.isConnected())
     {
         client.Connect();
     }
 }
コード例 #16
0
    public void joinServer()
    {
        TCPClient client = new TCPClient();

        client.Connect(hostAddress, port);
        Connected(client);
    }
コード例 #17
0
    // Use this for initialization
    void Start()
    {
        DontDestroyOnLoad(this);

        client = new TCPClient();
        client.ServerDomain = ServerDomain;
        client.spawnManager = GetComponent <SpawnManager>();
        client.Connect();
    }
コード例 #18
0
        private static void StartSSHTest()
        {
            TCPClient client = new TCPClient(new RealtimeProtocol());

            client.OnDisconnected += Client_OnDisconnected;
            client.OnReceived     += Client_OnReceive;
            client.Connect("192.168.3.222", 22);
            ZTImage.Log.Trace.Info("connect is starting");
        }
コード例 #19
0
        public void SendTest()
        {
            TCPClient tcpClient = new TCPClient();

            tcpClient.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000));
            var sendData = "Hello World";

            tcpClient.Send(Encoding.UTF8.GetBytes(sendData));
        }
コード例 #20
0
ファイル: WorldBot.cs プロジェクト: PsychoTeras/RatKing
 public void Connect()
 {
     if (_changingConnection || Connected)
     {
         return;
     }
     _changingConnection = true;
     _tcpClient.Connect();
 }
コード例 #21
0
 public void Connect(String IPAddress, int Port)
 {
     try
     {
         client.Connect(IPAddress, Port);
     } catch (Exception e) {
         Console.WriteLine(e.Message);
     }
 }
コード例 #22
0
ファイル: Debugger.cs プロジェクト: carcarjg/Uszka
        public void Start()
        {
            xClient = new TCPClient(port);
            xClient.Connect(ip, port);
            enabled = true;

            Send("--- Aura Debugger v0.2 ---");
            Send("Connected!");
            debugger.Send("Debugger started!");
        }
コード例 #23
0
 private void AsClient()
 {
     DisableBtn();
     client = new TCPClient();
     client.ReceiveCompleted    += Client_ReceiveCompleted;
     client.SendCompleted       += Client_SendCompleted;
     client.ConnectCompleted    += Client_ConnectCompleted;
     client.DisconnectCompleted += Client_DisconnectCompleted;
     client.Connect(new IPEndPoint(IPAddress.Parse("111.225.10.93"), 16550));
 }
コード例 #24
0
ファイル: Program.cs プロジェクト: icprog/MesCable
        static void Main(string[] args)
        {
            client = new TCPClient();
            client.ReceiveCompleted += Receive;
            client.Connect(new System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1"), 8686));
            byte[] data = Encoding.UTF8.GetBytes("hello");

            client.SendAsync(data);

            Console.ReadLine();
        }
コード例 #25
0
ファイル: Client.cs プロジェクト: Michal-MK/TCPrsi
 public void Connect(string ip, ushort port)
 {
     this.ipAddress = ip;
     this.port      = port;
     client         = new TCPClient(ip, port);
     client.SetUpClientInfo(string.Format("({0})-{1}", FindObjectOfType <Server>() != null ? "Server" : "Client", Environment.UserName));
     client.Connect();
     client.getConnection.OnStringReceived += OnStringReceived;
     SetUpTransmissionIds();
     DontDestroyOnLoad(gameObject);
 }
コード例 #26
0
ファイル: ClientProxy.cs プロジェクト: git4paulqu/Net
        public void Start()
        {
            TCPSetting clientSetting = TestDefine.GetTCPSetting();

            client = new TCPClient(clientSetting);
            client.onConnectCallback       += OnConnected;
            client.onConnectFailedCallback += OnConnectedFail;
            client.onClosedCallback        += OnCloseCallback;
            client.onReceiveCallback       += OnRevecie;
            client.Connect();
        }
コード例 #27
0
ファイル: Main.cs プロジェクト: rdodesigns/esoma
    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();
    }
コード例 #28
0
 public void Connect()
 {
     if (client.Connect())
     {
         logger.LogSuccess("Connect request has been sent! Response on event!");
     }
     else
     {
         logger.LogError("Failed to sent connect request!");
     }
 }
コード例 #29
0
 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();
 }
コード例 #30
0
        public void Run(string bootConf)
        {
            string  bootConfigText = ConfigHelper.LoadFromFile(bootConf);
            JObject bootConfig     = JObject.Parse(bootConfigText);

            m_tcpClient = new TCPClient();
            m_tcpClient.Start(0, OnSessionError, OnReadPacketComplete, OnConnectComplete);

            string gatewayHost = bootConfig["Gateway"]["Host"].ToString();

            string[] ipResult = gatewayHost.Split(':');
            string   gateIp   = ipResult[0];
            Int32    gatePort = Int32.Parse(ipResult[1]);

            m_tcpClient.Connect(gateIp, gatePort);

            m_isConnected = false;

            Console.WriteLine("Start Client... \n Please input message:");

            Random rand        = new Random(DateTime.Now.Millisecond);
            int    contentSize = rand.Next(5, 15);

            char[] arr     = { 'H', 'e', 'l', 'l', 'o' };
            string content = "";

            for (int i = 0; i < contentSize; i++)
            {
                content += arr[i % arr.Count()];
            }
            m_hashCode = content.GetHashCode();

            byte[] buffers = Encoding.ASCII.GetBytes(content);

            int increaceIndex = 0;

            while (true)
            {
                if (m_isConnected)
                {
                    Session session = m_tcpClient.GetSessionBy(m_userData.SessionId);
                    if (session != null && (increaceIndex % 5000 == 0))
                    {
                        session.Write(buffers);
                    }
                }

                increaceIndex++;

                m_tcpClient.Loop();
                Thread.Sleep(1);
            }
        }
コード例 #31
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world");
            Console.WriteLine("Enter the ip of the esp");
            string address = Console.ReadLine();

            while (true)
            {
                TCPClient client = new TCPClient(address, Constants.PORT);
                client.Connect();
            }
        }
コード例 #32
0
ファイル: ServerChecker.cs プロジェクト: rctl/QuickLink
 public static bool CheckServer(string ip)
 {
     try
     {
         TCPClient client = new TCPClient(ip, 1338);
         client.Connect();
         client.Send("close;");
         return true;
     }
     catch
     {
         return false;
     }
 }
コード例 #33
0
 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();
 }
コード例 #34
0
ファイル: sample18.cs プロジェクト: hyuntaeng/StarUML
        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());
            }
        }
コード例 #35
0
ファイル: Service.cs プロジェクト: rctl/QuickLink
        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);
        }