当前位置: 首页>>代码示例>>C#>>正文


C# TcpClient.Connect方法代码示例

本文整理汇总了C#中System.Net.Sockets.TcpClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.Connect方法的具体用法?C# TcpClient.Connect怎么用?C# TcpClient.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.TcpClient的用法示例。


在下文中一共展示了TcpClient.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Start

 public void Start(string[] args)
 {
     registry = new Registry();
     if (!registry.Register(this))
     {
         Console.WriteLine("Error registering service.");
         return;
     }
     Console.WriteLine("Registered service.");
     try
     {
         TcpClient tcpclient = new TcpClient();
         if (args.Count() != 2)
             throw new Exception("Argument must contain a publishing ip and port. call with: 127.0.0.1 12345");
         tcpclient.Connect(args[0], Int32.Parse(args[1]));
         StreamReader sr = new StreamReader(tcpclient.GetStream());
         string data;
         while ((data = sr.ReadLine()) != null)
         {
             Console.WriteLine("Raw data: " + data);
             if (RawAisData != null)
                 RawAisData(data);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message + e.StackTrace);
         Console.WriteLine("Press enter");
         Console.ReadLine();
     }
 }
开发者ID:Gohla,项目名称:protophase,代码行数:31,代码来源:RawAisPublisher.cs

示例2: Connect

 public void Connect()
 {
     if(_stream == null)
     {
         _client = new TcpClient();
         if (_config.host != null)
             _client.Connect(_config.host, _config.port);
         else
             _client.Connect(new IPEndPoint(IPAddress.Parse(_config.ip), _config.port));
         _stream = _client.GetStream();
     }
 }
开发者ID:onixion,项目名称:zeus,代码行数:12,代码来源:ZeusClient.cs

示例3: Connect

        public Boolean Connect()
        {
            try
            {
                if (recvThread != null)
                    recvThread.Abort();
            }
            catch (Exception ex)
            {
            }

            tcpClient = new TcpClient();
            try
            {

                tcpClient.Connect(ServerIP, Port);
                tcpClient.Client.Blocking = true;
                //tcpClient.Client.ReceiveTimeout = 1000;
                tcpClient.Client.LingerState = new LingerOption(true, 0);
                recvThread = new Thread(new ThreadStart(RecvRequestFromClient));
                recvThread.Start();
                IsConnected = true;
                return true;
            }
            catch (SocketException ex)
            {
                if (OnSocketError != null)
                    OnSocketError(0, new SocketEventArgs((int)ex.ErrorCode, ex.Message));                       
            }
            return false;
            
        }
开发者ID:MonetInfor,项目名称:MFCToolkit,代码行数:32,代码来源:CommTcpClient.cs

示例4: ConnectRemote

 private TcpClient ConnectRemote(IPEndPoint ipEndPoint)
 {
     TcpClient client = new TcpClient();
     try
     {
         client.Connect(ipEndPoint);
     }
     catch (SocketException socketException)
     {
         if (socketException.SocketErrorCode == SocketError.ConnectionRefused)
         {
             throw new ProducerException("服务端拒绝连接",
                                           socketException.InnerException ?? socketException);
         }
         if (socketException.SocketErrorCode == SocketError.HostDown)
         {
             throw new ProducerException("订阅者服务端尚未启动",
                                           socketException.InnerException ?? socketException);
         }
         if (socketException.SocketErrorCode == SocketError.TimedOut)
         {
             throw new ProducerException("网络超时",
                                           socketException.InnerException ?? socketException);
         }
         throw new ProducerException("未知错误",
                                           socketException.InnerException ?? socketException);
     }
     catch (Exception e)
     {
         throw new ProducerException("未知错误", e.InnerException ?? e);
     }
     return client;
 }
开发者ID:ssjylsg,项目名称:tcp-net,代码行数:33,代码来源:TcpPublish.cs

示例5: ListenerSocket

        /// <summary>
        /// Constructor
        /// </summary>
        public ListenerSocket()
        {
            // Init
            loadBalancerSocket = new TcpClient();

            // Connect to the loadbalancer
            Console.Write("Enter the loadbalancer ip: "); // Prompt
            loadBalancerSocket.Connect(IPAddress.Parse(Console.ReadLine()), int.Parse(Server.Properties.Resources.LoadBalancerPort));
            Logger.ShowMessage(
                String.Format("Connected to loadbalancer on: {0}:{1} and {2}:{3}",
                    ((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Address,
                    ((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Port,
                    ((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Address,
                    ((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Port
                )
            );

            Clients = new List<TcpClient>();
            messageHandler = new MessageHandler();

            // Make the socket listener and thread
            Random randomPort = new Random();
            listenerSocket = new TcpListener(IPAddress.Any, randomPort.Next(8900, 9000));
            listenThread = new Thread(new ThreadStart(ListenForClients));
            listenThread.Start();

            sendServerPort(loadBalancerSocket, ((IPEndPoint)listenerSocket.LocalEndpoint).Port);
            Logger.ShowMessage("Listener initialized.");
            Logger.ShowMessage("Listening on: " + ((IPEndPoint)listenerSocket.LocalEndpoint).Address + ":" + ((IPEndPoint)listenerSocket.LocalEndpoint).Port);

            // Define the handlers.
            PacketManager.DefineOpcodeHandlers();
        }
开发者ID:thebillkidy,项目名称:INF202A_DotNetDeel2,代码行数:36,代码来源:ListenerSocket.cs

示例6: Test

        public TestResultBase Test(Options o)
        {
            var p = new Uri(o.Url);

            var res = new GenericTestResult
            {
                ShortDescription = "TCP connection port " + p.Port,
                Status = TestResult.OK
            };

            try
            {
                var client = new TcpClient();
                client.Connect(p.DnsSafeHost, p.Port);
                res.Status = TestResult.OK;
                client.Close();
            }
            catch (Exception ex)
            {
                res.Status = TestResult.FAIL;
                res.CauseOfFailure = ex.Message;
            }

            return res;
        }
开发者ID:Be-MobileNV,项目名称:KvTestingTools,代码行数:25,代码来源:TcpConnectionTest.cs

示例7: Main

        static void Main(string[] args)
        {
            var port = Convert.ToInt32(args[0]);
              var timeout = Convert.ToInt32(args[1]);
              var buffer = new byte[12];

              client = new TcpClient();
              client.Connect(IPAddress.Loopback, port);
              client.Client.BeginReceive(termBuffer, 0, 1, SocketFlags.None,
                                 inputClient_DataReceived, null);

              Console.WriteLine("Connected to Nexus at 127.0.0.1:{0}", port);

              Wiimotes.ButtonClicked += Button;
              int numConnnected = Wiimotes.Connect(timeout);

              if (numConnnected > 0) {
            Console.WriteLine("{0} wiimote(s) found", numConnnected);

            CopyInt(ref buffer, 1, 0);
            CopyInt(ref buffer, numConnnected, 4);
            CopyInt(ref buffer, 0, 8);

            client.Client.Send(buffer);
            Wiimotes.Poll();
              }
              else {
            CopyInt(ref buffer, 1, 0);
            CopyInt(ref buffer, 0, 4);
            CopyInt(ref buffer, 0, 8);

            client.Client.Send(buffer);
            Console.WriteLine("No Wiimotes found");
              }
        }
开发者ID:synesthesiam,项目名称:nexus,代码行数:35,代码来源:WIICClient.cs

示例8: talk

 public bool talk()
 {
     try
     {
         if (null != sendPro)
         {
             TcpClient client = new TcpClient();
             client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)),
                 int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort)));
             NetworkStream ns = client.GetStream();
             IFormatter formatter = new BinaryFormatter();
             formatter.Serialize(ns, sendPro);
             reseivePro = (Protocol)formatter.Deserialize(ns);
             client.Close();
         }
         else
         {
             return false;
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
开发者ID:budlion,项目名称:DSTPRJ,代码行数:26,代码来源:NsTalk.cs

示例9: ConnectToServer

        public void ConnectToServer(string msg)
        {
            try
            {
                _client = new TcpClient();
                _client.Connect(_endPoint);

                byte[] bytes = Encoding.ASCII.GetBytes(msg);

                using (NetworkStream ns = _client.GetStream())
                {
                    Trace.WriteLine("Sending message to server: " + msg);
                    ns.Write(bytes, 0, bytes.Length);

                    bytes = new byte[1024];

                    int bytesRead = ns.Read(bytes, 0, bytes.Length);
                    string serverResponse = Encoding.ASCII.GetString(bytes, 0, bytesRead);

                    Trace.WriteLine("Server said: " + serverResponse);
                }
            }

            catch (SocketException se)
            {
                Trace.WriteLine("There was an error talking to the server: " + se.ToString());
            }

            finally
            {
                Dispose();
            }
        }
开发者ID:hftsai,项目名称:gulon-soft,代码行数:33,代码来源:MyTcpClient.cs

示例10: StartClient

        public void StartClient()
        {
            TcpClient tc = new TcpClient();

            tc.Connect("localhost", 9988);

            NetworkStream ns = tc.GetStream();

            List<byte> dataList = new List<byte>();

            //Node Id
            dataList.AddRange(BitConverter.GetBytes(1001));
            //Node Name
            dataList.AddRange(Encoding.ASCII.GetBytes("NK1001"));
            //Temperature
            dataList.AddRange(BitConverter.GetBytes((short)37));
            //Longitude
            dataList.AddRange(BitConverter.GetBytes((double)121.29));
            dataList.Add(0);

            byte[] data = dataList.ToArray();

            Console.WriteLine("Press <Enter> to send");
            while (Console.ReadLine() != null)
            {
                ns.Write(data, 0, data.Length);
            }
        }
开发者ID:haoxinyue,项目名称:Octopus,代码行数:28,代码来源:TestCase1.cs

示例11: Connect

        public Boolean Connect(String ip, int port)
        {
            try
            {
                TcpClient = new System.Net.Sockets.TcpClient();
                TcpClient.ReceiveTimeout = 5000;
                TcpClient.SendTimeout = 5000;
                TcpClient.Connect(ip, port);
                Ns = TcpClient.GetStream();

                Bw = new BinaryWriter(TcpClient.GetStream());
                Br = new BinaryReader(TcpClient.GetStream());

                IsConnected = true;
            }
            catch (Exception e)
            {
                IsConnected = false;
                Log.Cl(e.Message);
                return false;
            }

            ReceptionThread = new Thread(new ThreadStart(Run));
            ReceptionThread.IsBackground = true;
            ReceptionThread.Start();

            return true;
        }
开发者ID:eickegao,项目名称:Blazera,代码行数:28,代码来源:ClientConnection.cs

示例12: Connect

        public void Connect(string ip, int port = 8085)
        {
            _ip = ip;
            _port = port;

            _tcp = new TcpClient();
            _tcp.Connect(_ip, _port);

            _ns = _tcp.GetStream();

            ThreadPool.QueueUserWorkItem((x)=> {
                while(_tcp.Connected)
                {
                    try
                    {
                        if (_ns.DataAvailable)
                        {
                            byte[] buffer = new byte[4096];
                            int bytesread = _ns.Read(buffer, 0, buffer.Length);
                            Array.Resize(ref buffer, bytesread);

                            string msg = Encoding.UTF8.GetString(buffer);
                            HandlePacket(msg);
                        }
                    }
                    catch { }
                }
                _ns.Close();
                _ns.Dispose();
                _tcp.Close();
                Thread.CurrentThread.Abort();
            });
            
        }
开发者ID:Myvar,项目名称:MyvarServerNetwork,代码行数:34,代码来源:Client.cs

示例13: Parse

        private void Parse()
        {
            TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
            tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP
            System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
            sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client
            //bool flag = sslstream.IsAuthenticated; // check flag
            System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
            System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
            sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command
            sw.Flush(); // sent to server
            sw.WriteLine("PASS utybfkmyjcnm321");
            sw.Flush();
            sw.WriteLine("RETR 5");
            sw.Flush();
            sw.WriteLine("Quit "); // close the connection
            sw.Flush();
            string str = string.Empty;
            string strTemp = string.Empty;

            while ((strTemp = reader.ReadLine()) != null)
            {
                if (".".Equals(strTemp))
                {
                    break;
                }
                if (strTemp.IndexOf("-ERR") != -1)
                {
                    break;
                }
                str += strTemp;
            }

            MessageBox.Show(str);
        }
开发者ID:mrVengr,项目名称:Crypto,代码行数:35,代码来源:MainWindow.xaml.cs

示例14: Connect

        /// <summary>
        /// Connect TCP socket to a server.
        /// </summary>
        /// <param name="serverAddr">IP or hostname of server.</param>
        /// <param name="port">Port that TCP should use.</param>
        /// <returns>True if connection is successful otherwise false</returns>
        internal bool Connect(string serverAddr, int port)
        {
            try
            {
                IPAddress[] serverIP = Dns.GetHostAddresses(serverAddr);
                if (serverIP.Length <= 0)
                {
                    mErrorString = "Error looking up host name";
                    return false;
                }

                mTCPClient = new TcpClient();
                mTCPClient.Connect(serverIP[0], port);
                // Disable Nagle's algorithm
                mTCPClient.NoDelay = true;
            }
            catch (SocketException e)
            {
                mErrorString = e.Message;
                mErrorCode = e.SocketErrorCode;

                if (mTCPClient != null)
                {
                    mTCPClient.Close();
                }

                return false;
            }

            return true;
        }
开发者ID:qualisys,项目名称:RTClientSDK.Net,代码行数:37,代码来源:RTNetwork.cs

示例15: Button3_Click

 private void Button3_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Assembly executingAssembly = Assembly.GetExecutingAssembly();
         // load spim-generated data from embedded resource file
         const string spimDataName = "Simulation.Repressilator.txt";
         using (Stream spimStream = executingAssembly.GetManifestResourceStream(spimDataName))
         {
             using (StreamReader r = new StreamReader(spimStream))
             {
                 string line = r.ReadLine();
                 while (!r.EndOfStream)
                 {
                     TcpClient client = new TcpClient();
                     IPAddress ip1 = IPAddress.Parse(textBox1.Text.Trim());//{ 111, 186, 100, 46 }
                     client.Connect(ip1, 8500);
                     Stream streamToServer = client.GetStream();	// 获取连接至远程的流
                     line = r.ReadLine();
                     byte[] buffer = Encoding.Unicode.GetBytes(line);
                     streamToServer.Write(buffer, 0, buffer.Length);
                     streamToServer.Flush();
                     streamToServer.Close();
                     client.Close();
                     Thread.Sleep(10); // Long-long time for computations...
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
开发者ID:mxinshangshang,项目名称:CSharp_3D_WPF,代码行数:34,代码来源:Window1.xaml.cs


注:本文中的System.Net.Sockets.TcpClient.Connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。