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


C# Sockets.TcpClient类代码示例

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


TcpClient类属于System.Net.Sockets命名空间,在下文中一共展示了TcpClient类的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: 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


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