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


C# Sockets.TcpClient类代码示例

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


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

示例1: TryPrint

        public void TryPrint(string zplCommands)
        {
            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(this.m_IPAddress, this.m_Port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(zplCommands);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                this.m_ErrorCount += 1;
                if(this.m_ErrorCount < 10)
                {
                    System.Threading.Thread.Sleep(5000);
                    this.TryPrint(zplCommands);
                }
                else
                {
                    throw ex;
                }
            }
        }
开发者ID:ericramses,项目名称:YPILIS,代码行数:31,代码来源:ZPLPrinter.cs

示例2: ConnectionTask

        void ConnectionTask()
        {
            try
               {
               IsInConnectionTask=true;
               while (true)
               {
                   client = new System.Net.Sockets.TcpClient();
                   try
                   {
                       Console.WriteLine("try to  connect " + ip + ":" + port + " !");
                       client.Connect(ip, port);
                       Console.WriteLine(ip + ":" + port + "connected! ");
                   }
                   catch (Exception ex)
                   {
                       Console.WriteLine(ip + ":" + port + " " + ex.Message);
                   }

                   if (client.Connected)
                   {
                       new System.Threading.Thread(ReceiveTask).Start();
                       return;
                   }

               }
               }
               catch { ;}
               finally
               {
               IsInConnectionTask = false;
               }
        }
开发者ID:ufjl0683,项目名称:sshmc,代码行数:33,代码来源:RtkClient.cs

示例3: CreateAsync

 public static async Task<OpcWriter> CreateAsync(string host, int port = DefaultPort)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(host, port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
开发者ID:piers7,项目名称:PiCandy,代码行数:7,代码来源:OpcWriter.cs

示例4: Create

 public static OpcWriter Create(IPEndPoint target)
 {
     var client = new System.Net.Sockets.TcpClient();
     client.Connect(target.Address, target.Port);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
开发者ID:piers7,项目名称:PiCandy,代码行数:7,代码来源:OpcWriter.cs

示例5: chatHelper

        public chatHelper(Chat.Sockets.TcpClient tcpClient)
        {
            client = tcpClient;

            Thread chatThread = new Thread(new ThreadStart(startChat));
            chatThread.Start();
        }
开发者ID:rictortao,项目名称:Game-Lobby,代码行数:7,代码来源:chatHelper.cs

示例6: Start

        public bool Start()
        {
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);

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

            objSck = new System.Net.Sockets.TcpClient();

            try
            {
                objSck.Connect(ipAdd, port);
            }
            catch(Exception)
            {
                return false;
            }
            //catch (Exception)
            //{

            //    throw;
            //}

            //NetworkStreamを取得
            ns = objSck.GetStream();

            return true;
        }
开发者ID:terakenxx,项目名称:TukubaChallenge,代码行数:31,代码来源:TCPClient.cs

示例7: TcpClient

 public TcpClient(string hostName, int port)
 {
     _buffer = new byte[ReadSize];
     _tcpClient = new System.Net.Sockets.TcpClient(hostName, port);
     if (_tcpClient.Connected)
         _stream = _tcpClient.GetStream();
 }
开发者ID:ReactiveMarkets,项目名称:Styx.Client,代码行数:7,代码来源:TcpClient.cs

示例8: Request

        /// <summary>
        /// 
        /// </summary>
        /// <remarks>
        /// SocketException is resolved at higher level in the
        /// RemoteObjectProxyProvider.ProxyInterceptor.Intercept() method.
        /// </remarks>
        /// <param name="command"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="System.Net.Sockets.SocketException">
        /// When it is not possible to connect to the server.
        /// </exception>
        public string Request(string command, string[] data)
        {
            var client = new System.Net.Sockets.TcpClient(ServerAddress.IPAddress.ToString(), ServerAddress.Port);
            using (var clientStream = client.GetStream())
            {
                var sw = new StreamWriter(clientStream);

                command = command
                    .Replace("\r", TcpServer.CarriageReturnReplacement)
                    .Replace("\n", TcpServer.LineFeedReplacement);
                sw.WriteLine(command);

                sw.WriteLine(data.Length.ToString());
                foreach (string item in data)
                {
                    string encodedItem = item
                        .Replace("\r", TcpServer.CarriageReturnReplacement)
                        .Replace("\n", TcpServer.LineFeedReplacement);
                    sw.WriteLine(encodedItem);
                }

                sw.Flush();

                var sr = new StreamReader(clientStream);
                string result = sr.ReadLine();
                if (result != null)
                {
                    result = result
                        .Replace(TcpServer.CarriageReturnReplacement, "\r")
                        .Replace(TcpServer.LineFeedReplacement, "\n");
                }
                return result;
            }
        }
开发者ID:bzamecnik,项目名称:XRouter,代码行数:47,代码来源:TcpClient.cs

示例9: Main

        static void Main(string[] args)
        {
            Protocol protocol;
             string ip;
             int port;
             V2DLE dle;
             System.Net.Sockets.TcpClient tcp;
            protocol = new Protocol();
            protocol.Parse(System.IO.File.ReadAllText(Protocol.CPath(AppDomain.CurrentDomain.BaseDirectory+"TIME.txt")),false);
            ip = protocol.ip;
            port = protocol.port;

            while (true)
            {
                try
                {
                    bool isCommErr = false;
                    tcp = new System.Net.Sockets.TcpClient();
                    tcp = ConnectTask(ip, port);
                    dle = new V2DLE("DigitTimer", tcp.GetStream());
                    dle.OnCommError+=(s,a)=>
                        {
                            isCommErr = true;
                            dle.Close();
                        };
                    while (!isCommErr)
                    {

                        System.Data.DataSet ds = protocol.GetSendDataSet("report_system_time");
                        SendPackage pkg = protocol.GetSendPackage(ds, 0xffff);
                        pkg.cls = CmdClass.A;
                        dle.Send(pkg);
                        if (pkg.result == CmdResult.ACK)
                        {
                            System.Data.DataSet retDs = protocol.GetReturnDsByTextPackage(pkg.ReturnTextPackage);
                            int yr,mon,dy,hr,min,sec;
                            yr=System.Convert.ToInt32(retDs.Tables[0].Rows[0]["year"]);
                            mon = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["month"]);
                            dy = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["day"]);
                            hr = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["hour"]);
                            min = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["minute"]);
                            sec = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["second"]);
                             DateTime dt = new DateTime(yr, mon, dy, hr, min, sec);
                             Console.WriteLine(dt.ToString());
                             RemoteInterface.Util.SetSysTime(dt);
                        }
                        else
                        {
                            Console.WriteLine(pkg.result.ToString());
                        }

                        System.Threading.Thread.Sleep(1000 * 60 );
                    }
                }
                catch (Exception ex)
                {
                    ;
                }
            }
        }
开发者ID:ufjl0683,项目名称:Center,代码行数:60,代码来源:Program.cs

示例10: OpenAsync

        /// <summary>
        /// Open 通信要求受付(非同期)
        /// </summary>
        /// <param name="ipAddr">IPアドレス</param>
        /// <param name="ipPort">ポート</param>
        /// <returns></returns>
        public async void OpenAsync()
        {
            sw.Start();

            //ListenするIPアドレス
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(listenIP);

            //TcpListenerオブジェクトを作成する
            listener =
                new System.Net.Sockets.TcpListener(ipAdd, listenPort);

            //Listenを開始する
            listener.Start();
            Console.WriteLine("Listenを開始しました({0}:{1})。",
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            //client = listener.AcceptTcpClient();
            try
            {
                client = await listener.AcceptTcpClientAsync();
                Console.WriteLine("クライアント({0}:{1})と接続しました。",
                    ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                    ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

                //NetworkStreamを取得
                ns = client.GetStream();
            }
            catch (Exception)
            {
            }
        }
开发者ID:terakenxx,项目名称:TukubaChallenge,代码行数:39,代码来源:SCIPsim.cs

示例11: printButton_Click

        private void printButton_Click(object sender, EventArgs e)
        {
            // Printer IP Address and communication port
            string ipAddress = printerIpText.Text;
            int port = 9100;

            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(ipAddress, port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(zplCode);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
                MessageBox.Show("Print Successful!", "Success");
                this.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex);
                MessageBox.Show("No printer installed corresponds to the IP address given", "No response");
            }
        }
开发者ID:aditya7iyengar,项目名称:Label-Viewer,代码行数:29,代码来源:PrintLabel.cs

示例12: Connect

        private static bool Connect(string friendly)
        {
            try
            {
                client = new System.Net.Sockets.TcpClient();
                TVServer.MPClient.Client mpclient = uWiMP.TVServer.MPClientDatabase.GetClient(friendly);

                if (mpclient.Hostname == string.Empty)
                {
                    host = friendly;
                }
                else
                {
                    host = mpclient.Hostname;
                }

                if (mpclient.Port == string.Empty)
                {
                    port = DEFAULT_PORT;
                }
                else
                {
                    port = Convert.ToInt32(mpclient.Port);
                }

                client.Connect(host, port);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
开发者ID:rndthoughts,项目名称:ipimpplus,代码行数:34,代码来源:MPClientTCPRemoting.cs

示例13: connect

        public static string connect(String server,int port,String ouath)
        {
            System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient ();
            sock.Connect (server, port);
            if (!sock.Connected) {
                Console.Write ("not working hoe");

            }
            System.IO.TextWriter output;
            System.IO.TextReader input;
            output = new System.IO.StreamWriter (sock.GetStream ());
            input = new System.IO.StreamReader (sock.GetStream ());
            output.Write (

                "PASS " + ouath + "\r\n" +
                "NICK " + "Sail338" + "\r\n" +
                "USER " + "Sail338" + "\r\n" +
                "JOIN " 	+ "#sail338" + "" + "\r\n"

            );
            output.Flush ();

            for (String rep = input.ReadLine ();; rep = input.ReadLine ()) {
                string[] splitted = rep.Split (':');
                if (splitted.Length > 2) {
                    string potentialVote = splitted [2];
                    if (Array.Exists (validVotes, vote => vote.Equals(potentialVote)))
                        return potentialVote;
                }
            }
        }
开发者ID:vanstorm9,项目名称:TwitchCollaborativePartyGame,代码行数:31,代码来源:Program.cs

示例14: CheckPort

        public static bool CheckPort(string ip, int port, int timeout)
        {
            using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(ip, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
                    {
                        tcp.Close();
                        throw new TimeoutException();
                    }

                    tcp.EndConnect(ar);

                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
                finally
                {
                    wh.Close();
                }
            }
        }
开发者ID:skt90u,项目名称:skt90u-framework-dotnet,代码行数:28,代码来源:Net.cs

示例15: openSocket

		/*
		* 
		*/
		public virtual void  openSocket()
		{
			socket = new System.Net.Sockets.TcpClient(host, port);
			socket.LingerState = new System.Net.Sockets.LingerOption(true, 1000);
			
			os = socket.GetStream();
			is_Renamed = socket.GetStream();
		}
开发者ID:xuchuansheng,项目名称:GenXSource,代码行数:11,代码来源:NuGenHL7ServerTestHelper.cs


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