• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Sockets.TcpClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



TcpClient类属于System.Net.Sockets命名空间,在下文中一共展示了TcpClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: Client

        /// <summary>
        /// 客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="message"></param>
        static void Client(string ip, int port, string message)
        {
            try
            {
                //1.发送数据
                TcpClient client = new TcpClient(ip, port);
                IPEndPoint ipendpoint = client.Client.RemoteEndPoint as IPEndPoint;
                NetworkStream stream = client.GetStream();
                byte[] messages = Encoding.Default.GetBytes(message);
                stream.Write(messages, 0, messages.Length);
                Console.WriteLine("{0:HH:mm:ss}->发送数据(to {1}):{2}", DateTime.Now, ip, message);

                //2.接收状态,长度<1024字节
                byte[] bytes = new Byte[1024];
                string data = string.Empty;
                int length = stream.Read(bytes, 0, bytes.Length);
                if (length > 0)
                {
                    data = Encoding.Default.GetString(bytes, 0, length);
                    Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2}):{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
                }

                //3.关闭对象
                stream.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
            }
            Console.ReadKey();
        }
开发者ID:LovingYao,项目名称:myProgram,代码行数:38,代码来源:TcpClientDemo.cs


示例3: ServerConnection

 public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter)
 {
     _client = client;
     _stream = stream;
     _binaryReader = binaryReader;
     _binaryWriter = binaryWriter;
 }
开发者ID:OrcusTechnologies,项目名称:Orcus.Plugins.ServerStressTest,代码行数:7,代码来源:ServerConnection.cs


示例4: ThreadClient

 public ThreadClient(TcpClient cl, int i)
 {
     this.cl = cl;
     tuyen = new Thread(new ThreadStart(GuiNhanDL));
     tuyen.Start();
     this.i = i;
 }
开发者ID:pthdnq,项目名称:csharp-project-nduang,代码行数:7,代码来源:Program.cs


示例5: Client

        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
开发者ID:Team7-SoftEng,项目名称:GateofGabethulu-launcher,代码行数:27,代码来源:Client.cs


示例6: Connect

 public void Connect(IPEndPoint remoteAddress)
 {
     BaseSocket = new TcpClient();
     BaseSocket.Connect(remoteAddress);
     OutputStream = new StreamWriter(new BufferedStream(BaseSocket.GetStream()));
     InputStream = new StreamReader(new BufferedStream(BaseSocket.GetStream()));
 }
开发者ID:CookieEaters,项目名称:FireHTTP,代码行数:7,代码来源:AlligatorWaffleClient.cs


示例7: bnConnect_Click

        private void bnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient(txtConnect.Text, 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);
                dato = sr.ReadLine()
                    + System.Environment.NewLine
                    + sr.ReadLine()
                    + System.Environment.NewLine
                    + sr.ReadLine();

                DelegadoRespuesta dr = new DelegadoRespuesta(EscribirFormulario);
                Invoke(dr);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                throw;
            }


        }
开发者ID:Maldercito,项目名称:psp,代码行数:26,代码来源:1453365614$Form1.cs


示例8: handleClient

        private void handleClient(TcpClient socket)
        {
            string data;
            NetworkStream ns = socket.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);


            sw.WriteLine("Benvido, intenta adivinar o meu número");
            sw.Flush();


            try
            {
                while (true)
                {
                }
            }
            catch (Exception)
            {

                throw;
            }



        }
开发者ID:Maldercito,项目名称:psp,代码行数:27,代码来源:1447660623$Form1.cs


示例9: Jeu

 //private volatile bool gameStarted = false;
 public Jeu()
 {
     State = GameState.WaitingStartGame;
     serveur = new TcpClient("P104-14", 8080);
     Attente = new Thread(AttendreDebutPartie);
     Attente.Start();
 }
开发者ID:Pouletgrill,项目名称:BattleShipClient,代码行数:8,代码来源:Jeu.cs


示例10: Connect

        public void Connect(String server, String message)
        {
            try
            {


                Int32 port = 13000;
                client = new TcpClient(server, port);
                while (true)
                {
                    Recieve();
                    //Send();
                   

                }
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

            Console.WriteLine("\n Press Enter to continue...");
            Console.Read();
        }
开发者ID:kevinnieskes,项目名称:Game,代码行数:28,代码来源:Join.cs


示例11: handleClient

        private void handleClient(TcpClient socket)
        {
            String rawData;
            String data;
            NetworkStream ns = socket.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);

            sw.WriteLine("@[email protected]@");
            sw.Flush();

            while (true)
            {
                try
                {
                    // do things
                    rawData = sr.ReadLine();

                    Console.WriteLine("Raw data: " + rawData); // debug
                    data = hexaToString(rawData);
                    Console.WriteLine("String data: " + data); // debug
                }
                catch (Exception err)
                {
                    //Console.WriteLine(err.ToString());
                    break;
                }

            }

            ns.Close();
            socket.Close();
            //  finish

        }
开发者ID:Maldercito,项目名称:geoworks,代码行数:35,代码来源:1456129723$Form1.cs


示例12: TcpListenerWebSocketContext

    internal TcpListenerWebSocketContext (
      TcpClient tcpClient,
      string protocol,
      bool secure,
      ServerSslConfiguration sslConfig,
      Logger logger)
    {
      _tcpClient = tcpClient;
      _secure = secure;
      _logger = logger;

      var netStream = tcpClient.GetStream ();
      if (secure) {
        var sslStream = new SslStream (
          netStream, false, sslConfig.ClientCertificateValidationCallback);

        sslStream.AuthenticateAsServer (
          sslConfig.ServerCertificate,
          sslConfig.ClientCertificateRequired,
          sslConfig.EnabledSslProtocols,
          sslConfig.CheckCertificateRevocation);

        _stream = sslStream;
      }
      else {
        _stream = netStream;
      }

      _request = HttpRequest.Read (_stream, 90000);
      _uri = HttpUtility.CreateRequestUrl (
        _request.RequestUri, _request.Headers["Host"], _request.IsWebSocketRequest, secure);

      _websocket = new WebSocket (this, protocol);
    }
开发者ID:yakolla,项目名称:HelloVertX,代码行数:34,代码来源:TcpListenerWebSocketContext.cs


示例13: TcpTextWriter

        public TcpTextWriter(string hostName, int port)
        {
            if (hostName == null)
                throw new ArgumentNullException(nameof(hostName));
            if ((port < 0) || (port > ushort.MaxValue))
                throw new ArgumentException("port");

            HostName = hostName;
            Port = port;

#if __IOS__ || MAC
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
#endif
            try
            {
#if __IOS__ || MAC || ANDROID
                var client = new TcpClient(hostName, port);
                writer = new StreamWriter(client.GetStream());
#elif WINDOWS_PHONE || NETFX_CORE
               
                var socket = new StreamSocket();
                socket.ConnectAsync(new HostName(hostName), port.ToString(CultureInfo.InvariantCulture))
                    .AsTask()
                    .ContinueWith( _ => writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()));
#endif
            }
            catch
            {
#if __IOS__ || MAC
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
#endif
                throw;
            }
        }
开发者ID:roubachof,项目名称:devices.xunit,代码行数:34,代码来源:TcpTextWriter.cs


示例14: Agent

        private Thread ziThread; //处理客户端请求的线程

        #endregion Fields

        #region Constructors

        public Agent(TcpClient client, NetworkStream streamToClient, string DataSourceIpOrPortA, string DataSourceIpOrPortB)
        {
            this.client = client;
            this.streamToClient = streamToClient;
            this.DataSourceIpOrPortA = DataSourceIpOrPortA;
            this.DataSourceIpOrPortB = DataSourceIpOrPortB;
        }
开发者ID:find-life,项目名称:KIOSKWindowService,代码行数:13,代码来源:Agent.cs


示例15: TcpSocket

 public TcpSocket(TcpClient tcpClient)
 {
     this._connection = tcpClient;
     this._connection.NoDelay = true;
     IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
     this._remoteAddress = (RemoteAddress)new TcpAddress(ipEndPoint.Address, ipEndPoint.Port);
 }
开发者ID:EmuDevs,项目名称:EDTerraria,代码行数:7,代码来源:TcpSocket.cs


示例16: User

 public User(TcpClient client)
 {
     this.client = client;
     NetworkStream networkStream = client.GetStream();
     br = new BinaryReader(networkStream);
     bw = new BinaryWriter(networkStream);
 }
开发者ID:Code-Fight,项目名称:SocketServer,代码行数:7,代码来源:User.cs


示例17: TestListen

        public void TestListen()
        {
            try
            {
                Identd.Start("username");
                Thread.Sleep( 1000 );

                TcpClient client = new TcpClient();
                client.Connect("localhost", 113);

                StreamWriter writer = new StreamWriter( client.GetStream() );
                writer.WriteLine( "a query" );
                writer.Flush();

                StreamReader reader = new StreamReader( client.GetStream() );
                string line = reader.ReadLine();

                Identd.Stop();

                Assertion.AssertEquals( "a query : USERID : UNIX : username", line.Trim() );
            }
            catch( Exception e )
            {
                Assertion.Fail("IO Exception during test:" + e);
            }
        }
开发者ID:Iciclebar,项目名称:ThreshIRC,代码行数:26,代码来源:IdentdTest.cs


示例18: 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


示例19: RunClient

        static void RunClient(object state)
        {
            Customer cust = Customer.Invent();
            Console.WriteLine("CLIENT: Opening connection...");
            using (TcpClient client = new TcpClient())
            {
                client.Connect(new IPEndPoint(IPAddress.Loopback, PORT));
                using (NetworkStream stream = client.GetStream())
                {
                    Console.WriteLine("CLIENT: Got connection; sending data...");
                    Serializer.SerializeWithLengthPrefix(stream, cust, PrefixStyle.Base128);
                    
                    Console.WriteLine("CLIENT: Attempting to read data...");
                    Customer newCust = Serializer.DeserializeWithLengthPrefix<Customer>(stream, PrefixStyle.Base128);
                    Console.WriteLine("CLIENT: Got customer:");
                    newCust.ShowCustomer();

                    Console.WriteLine("CLIENT: Sending happy...");
                    stream.WriteByte(123); // just to show all bidirectional comms are OK
                    Console.WriteLine("CLIENT: Closing...");
                    stream.Close();
                }
                client.Close();
            }
        }
开发者ID:Erguotou,项目名称:protobuf-net,代码行数:25,代码来源:3+Sockets.cs


示例20: 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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Sockets.TcpListener类代码示例发布时间:2022-05-26
下一篇:
C# Sockets.StateObject类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap