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


C# TcpClient.Close方法代码示例

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


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

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

示例2: GetData

 /// <summary>
 /// Attempts to gets data from the other computer in a LAN game
 /// </summary>
 /// <param name="Client">The specified other computer</param>
 /// <returns>The string representing the data recieved, or a blank string if the other computer disconnected</returns>
 public static string GetData(TcpClient Client)
 {
     NetworkStream tStream = Client.GetStream();
     if (tStream.CanRead && Client.Connected)
     {
         Byte[] recievedBytes = new byte[buffersize];
         try
         {
             tStream.Read(recievedBytes, 0, buffersize);
         }
         catch (Exception ex)
         {
             Game.PauseGame("Opponent has disconnected, press ESC to return to main menu.");
             Client.Close();
             return "";
         }
         int culSize = 0;
         for (int i = 0; i < bytestotellsize; i++)
             culSize += recievedBytes[i];
         Byte[] inp = new byte[culSize];
         Array.ConstrainedCopy(recievedBytes, bytestotellsize, inp, 0, culSize);
         return System.Text.Encoding.ASCII.GetString(inp);
     }
     Game.PauseGame("Opponent has disconnected, press ESC to return to main menu.");
     Client.Close();
     return "";
 }
开发者ID:WGDEVS,项目名称:SeaBattle,代码行数:32,代码来源:LanHost.cs

示例3: PrimaryProcess

        static void PrimaryProcess(int initval = 0)
        {
            int i = initval;
            Console.WriteLine("I am primary!");
            Process.Start("TCPProcessPair.exe", string.Format("{0} -backup", port));

            TcpClient client = null;
            try
            {
                client = new TcpClient("localhost", port);
                Stream s = client.GetStream();
                StreamWriter sw = new StreamWriter(s);
                sw.AutoFlush = true;
                for (i = initval; true; ++i)
                {
                    Console.WriteLine(i);
                    sw.WriteLine(i);
                    Thread.Sleep(1000);
                }
            }
            catch (IOException)
            {
                if (client != null) client.Close();
                Console.WriteLine("Wanna continue? yes/no");
                string answer = Console.ReadLine();
                if (answer.Equals("yes"))       // without 'if' the process is infinite,
                    PrimaryProcess(i + 1);      // whether primary or backup are killed
            }
            finally
            {
                if (client != null) client.Close();
            }
        }
开发者ID:DanglingPointer,项目名称:TTK4145,代码行数:33,代码来源:TCPProcessPair.cs

示例4: connect_sync

        public NetworkStream connect_sync()
        {
            try
            {
                ConnectionStatistics.numberOfConnections++;
                //Establish a connection to the node
                channel = new TcpClient();
                channel.Connect(node.GetEndPoint());

                //Get a stream to the node
                stream = channel.GetStream();
                ConnectionStatistics.numberOfConnections++;

                if(stream == null)
                {
                    ConnectionStatistics.missedConnections++;
                    channel.Close();
                    return null;
                }

                if(!stream.CanRead || !stream.CanWrite)
                {
                    ConnectionStatistics.noReadWritePermissions++;
                    stream.Close();
                    channel.Close();
                    return null;
                }
            }
            catch
            {
                return null;
            }
            return stream;
        }
开发者ID:beghbali,项目名称:ResourceRingEntropyNetwork,代码行数:34,代码来源:Connection.cs

示例5: DoPing

 public static ServerStatus DoPing(IPEndPoint endPoint, string hostname = null)
 {
     var client = new TcpClient();
     client.Connect(endPoint);
     var manager = new NetworkManager(client.GetStream());
     manager.WritePacket(new HandshakePacket(
         NetworkManager.ProtocolVersion,
         hostname ?? endPoint.Address.ToString(),
         (ushort)endPoint.Port,
         NetworkMode.Status), PacketDirection.Serverbound);
     manager.WritePacket(new StatusRequestPacket(), PacketDirection.Serverbound);
     var _response = manager.ReadPacket(PacketDirection.Clientbound);
     if (!(_response is StatusResponsePacket))
     {
         client.Close();
         throw new InvalidOperationException("Server returned invalid ping response");
     }
     var response = (StatusResponsePacket)_response;
     var sent = DateTime.Now;
     manager.WritePacket(new StatusPingPacket(sent.Ticks), PacketDirection.Serverbound);
     var _pong = manager.ReadPacket(PacketDirection.Clientbound);
     if (!(_pong is StatusPingPacket))
     {
         client.Close();
         throw new InvalidOperationException("Server returned invalid ping response");
     }
     client.Close();
     var pong = (StatusPingPacket)_pong;
     var time = new DateTime(pong.Time);
     response.Status.Latency = time - sent;
     return response.Status;
 }
开发者ID:Booser,项目名称:Craft.Net,代码行数:32,代码来源:ServerPing.cs

示例6: RunClient

            public static string RunClient(string serverName,string activation_info,ref string buffer)
            {                                
                TcpClient client = new TcpClient(serverName,443);                
                SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );
              
                try
                {
                    sslStream.AuthenticateAsClient(serverName);
                }
                catch (AuthenticationException e)
                {   
                    if (e.InnerException != null)
                    {
                    }
                    client.Close();
                    Environment.Exit(-1);
                }

                byte[] messsage = Encoding.UTF8.GetBytes(activation_info + "\n<EOF>");                
                sslStream.Write(messsage);
                sslStream.Flush();               
                string serverMessage = ReadMessage(sslStream);                
                client.Close();                
                buffer = serverMessage;
                return serverMessage;
            }
开发者ID:rAbd0u,项目名称:iactivator,代码行数:31,代码来源:SslTcpClient.cs

示例7: ConnValidate

        public static bool ConnValidate(String host, int port, int timeoutMSec)
        {
            bool ret = false;
            timeoutObject.Reset();
            socketException = null;

            TcpClient tcpClient = new TcpClient();
            tcpClient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpClient);

            if (timeoutObject.WaitOne(timeoutMSec, false))
            {
                if (IsConnectionSuccessful)
                {
                    ret = true;
                    tcpClient.Close();
                }
                else
                {
                    //throw socketException;
                }
            }
            else
            {
                //throw new TimeoutException();
            }
            tcpClient.Close();

            return ret;
        }
开发者ID:g992com,项目名称:esb,代码行数:29,代码来源:NetPortON.cs

示例8: processClient

        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
开发者ID:bemk,项目名称:rhc,代码行数:34,代码来源:SslTcpServer.cs

示例9: Sendmessage

        /// <summary>
        /// msg发送的内容
        /// </summary>
        /// <param name="msgs"></param>
        /// <returns>true发送成功 flase发送失败</returns>
        public void Sendmessage(String msgs)
        {
//            String responseData = null;
            TcpClient client = null;
            NetworkStream stream = null;
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer 
                // connected to the same address as specified by the server, port
                // combination.
                client = new TcpClient(_address, _uport);

                // Translate the passed message into ASCII and store it as a Byte array.
                Byte[] data = Encoding.ASCII.GetBytes(msgs);

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                stream = client.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);

                Console.WriteLine("Sent: {0}", msgs);

                // Receive the TcpServer.response.

                // Buffer to store the response bytes.
//                data = new Byte[256];

                // String to store the response ASCII representation.
//                responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes. 
//                Int32 bytes = stream.Read(data, 0, data.Length);
//                responseData = Encoding.ASCII.GetString(data, 0, bytes);
//                Console.WriteLine("Received: {0}", responseData);

                // Close everything.
                stream.Close();
                client.Close();

            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
                stream.Close();
                client.Close();
                throw;
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
                throw;
            }
        }
开发者ID:ChenJingLei,项目名称:SmartEl,代码行数:62,代码来源:Client.cs

示例10: DownloadData

        public static byte[] DownloadData(string url, Action<int, int> f, int chunkSize)
        {
            var uri = new Uri(url);
            var ip = Dns.GetHostEntry(uri.DnsSafeHost).AddressList[0];

            using (var s = new TcpClient())
            {
                s.Connect(new IPEndPoint(ip, uri.Port));
                var ns = s.GetStream();
                var sw = new StreamWriter(ns);

                sw.Write("GET {0} HTTP/1.0\r\nHost:{1}\r\n\r\n", uri.PathAndQuery, uri.Host);
                sw.Flush();

                var br = new BinaryReader(ns);
                var contentLength = 0;
                var offset = 0;
                for (; ; )
                {
                    var result = br.ReadLine();
                    var kv = result.Split(new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries);

                    if (result == "")
                    {
                        /* data follows the blank line */

                        if (contentLength > 0)
                        {
                            if (f != null)
                                f(offset, contentLength);

                            var data = new byte[contentLength];
                            while (offset < contentLength)
                            {
                                var thisChunk = Math.Min(contentLength - offset, chunkSize);
                                br.Read(data, offset, thisChunk);
                                offset += thisChunk;
                                if (f != null)
                                    f(offset, contentLength);
                            }
                            s.Close();
                            return data;
                        }
                        else
                        {
                            s.Close();
                            return new byte[] { };
                        }
                    }
                    else if (kv[0] == "Content-Length")
                        contentLength = int.Parse(kv[1]);
                }
            }
        }
开发者ID:hoxworth,项目名称:OpenRA,代码行数:54,代码来源:HttpUtil.cs

示例11: sendMessage

 public void sendMessage(RemoteOverlayMessagingLib.Messages.IOverlayMessage message, String host)
 {
     TcpClient tcpConnection = new TcpClient(host, 11253);
     if (tcpConnection.Connected)
     {
         byte[] body = message.createNetworkMessage();
         byte[] header = RemoteOverlayMessagingLib.MessageEncoder.createMessageHeader(message.getMessageId(), body.Length);
         tcpConnection.Client.Send(header, header.Length, SocketFlags.None);
         tcpConnection.Client.Send(body, body.Length, SocketFlags.None);
         tcpConnection.ReceiveTimeout = 20000;
         byte[] recHeader = new byte[8];
         int index = 0;
         while (index < 8)
         {
             int count = tcpConnection.Client.Receive(recHeader, index, 8 - index, SocketFlags.None);
             index += count;
         }
         Int32 messageId = new Int32();
         Int32 length = new Int32();
         RemoteOverlayMessagingLib.MessageEncoder.decodeMessageHeader(recHeader, ref messageId, ref length);
         if (messageId == RemoteOverlayMessagingLib.Messages.ConfirmMessage.MessageId)
         {
             byte[] recBody = new byte[length];
             index = 0;
             while (index < length)
             {
                 int count = tcpConnection.Client.Receive(recBody, index, length - index, SocketFlags.None);
                 index += count;
             }
             try
             {
                 RemoteOverlayMessagingLib.Messages.ConfirmMessage conf = new RemoteOverlayMessagingLib.Messages.ConfirmMessage(recBody, length);
             }
             catch (Exception)
             {
                 // Did not receive confirmation
                 tcpConnection.Close();
                 throw new Exception("Recieved invalid confirmation data");
             }
         }
         else
         {
             tcpConnection.Close();
             throw new Exception("Recieved invalid confirmation message");
         }
     }
     else
     {
         tcpConnection.Close();
         throw new Exception("Could not connect to server");
     }
     tcpConnection.Close();
 }
开发者ID:dcroper,项目名称:RemoteOverlay,代码行数:53,代码来源:MessagingClient.cs

示例12: SendRaw

        public static void SendRaw(string hostname, int tunnelPort, System.IO.Stream clientStream)
        {
            System.Net.Sockets.TcpClient tunnelClient = null;
            NetworkStream tunnelStream = null;

            try
            {
                tunnelClient = new System.Net.Sockets.TcpClient(hostname, tunnelPort);

                tunnelStream = tunnelClient.GetStream();

                var tunnelReadBuffer = new byte[BUFFER_SIZE];

                Task sendRelay = Task.Factory.StartNew(() => StreamHelper.CopyTo(clientStream, tunnelStream, BUFFER_SIZE));
                Task receiveRelay = Task.Factory.StartNew(() => StreamHelper.CopyTo(tunnelStream, clientStream, BUFFER_SIZE));

                sendRelay.Start();
                receiveRelay.Start();

                Task.WaitAll(sendRelay, receiveRelay);
            }
            catch
            {
                if (tunnelStream != null)
                {
                    tunnelStream.Close();
                    tunnelStream.Dispose();
                }

                if (tunnelClient != null)
                    tunnelClient.Close();

                throw;
            }
        }
开发者ID:jachaos,项目名称:Titanium,代码行数:35,代码来源:Tcp.cs

示例13: Invoke

		public void Invoke()
		{
			var uri = this.Target;
			var t = new TcpClient();

			t.Connect(uri.Host, this.Port);

			//var w = new StreamWriter(t.GetStream());

			var w = new StringBuilder();

			w.AppendLine("GET" + " " + uri.PathAndQuery + " HTTP/1.1");
			w.AppendLine("Host: " + uri.Host);
			w.AppendLine("Connection: Close");

			// http://www.botsvsbrowsers.com/
			w.Append(@"User-Agent: jsc
Referer: " + this.Referer + @"
Accept:  */*
Accept-Encoding:  gzip,deflate
Accept-Language:  et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset:  windows-1257,utf-8;q=0.7,*;q=0.3
");
			w.AppendLine();

			var data = Encoding.UTF8.GetBytes(w.ToString());

			t.GetStream().Write(data, 0, data.Length);

			// it will take up to a minute to show up
			t.Close();
		}
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:32,代码来源:TrivialWebRequest.cs

示例14: sendButton_Click

        private void sendButton_Click(object sender, EventArgs e)
        {
            BulletinMessage msg = new BulletinMessage();
            msg.Content = this.messageBox.Text;
            msg.Timestamp = DateTime.Now;

            this.statusLogBox.AppendText("CLIENT: Opening connection" + Environment.NewLine);

            using (TcpClient client = new TcpClient())
            {
                client.Connect(IPAddress.Loopback, 8888);

                using (NetworkStream stream = client.GetStream())
                {
                    this.statusLogBox.AppendText("CLIENT: Got connection; sending message..." + Environment.NewLine);
                    this.statusLogBox.AppendText(msg.ToString() + Environment.NewLine);

                    // send data to server
                    Serializer.SerializeWithLengthPrefix(stream, msg, PrefixStyle.Base128);

                    this.statusLogBox.AppendText("CLIENT: Closing connection" + Environment.NewLine);
                    stream.Close();
                }

                client.Close();
            }
        }
开发者ID:khchanel,项目名称:TcpBulletin,代码行数:27,代码来源:BulletinForm.cs

示例15: CheckMinecraft

        public void CheckMinecraft()
        {
            if (!NeedToUpdate("minecraft", 30))
                return;

            TcpClient tcp = new TcpClient();
            try
            {
                tcp.SendTimeout = 2000;
                tcp.ReceiveTimeout = 2000;
                tcp.NoDelay = true;
                tcp.Client.ReceiveTimeout = 2000;
                tcp.Client.SendTimeout = 2000;

                var async = tcp.BeginConnect(MinecraftHost, MinecraftPort, null, null);
                DateTime dt = DateTime.Now;
                while ((DateTime.Now - dt).TotalSeconds < 3 && !async.IsCompleted)
                    System.Threading.Thread.Sleep(40);
                if (!async.IsCompleted)
                {
                    try
                    {
                        tcp.Close();
                    }
                    catch { { } }
                    MinecraftOnline = false;
                    return;
                }

                if (!tcp.Connected)
                {
                    log.Fatal("Minecraft server is offline.");
                    MinecraftOnline = false;
                    return;
                }

                var ns = tcp.GetStream();
                var sw = new StreamWriter(ns);
                var sr = new StreamReader(ns);

                ns.WriteByte(0xFE);

                if (ns.ReadByte() != 0xFF)
                    throw new Exception("Invalid data");

                short strlen = BitConverter.ToInt16(ns.ReadBytes(2), 0);
                string strtxt = Encoding.BigEndianUnicode.GetString(ns.ReadBytes(2 * strlen));

                string[] strdat = strtxt.Split('§'); // Description§Players§Slots[§]
                MinecraftOnline = true;
                MinecraftSvrDescription = strdat[0];
                MinecraftCurPlayers = ulong.Parse(strdat[1]);
                MinecraftMaxPlayers = ulong.Parse(strdat[2]);
            }
            catch (Exception n)
            {
                log.Fatal("Minecraft server check error: " + n);
                MinecraftOnline = false;
            }
        }
开发者ID:bobolo,项目名称:fourdeltaone-status,代码行数:60,代码来源:SSMinecraftCheck.cs


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