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


C# TcpClient.Close方法代码示例

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


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

示例1: HandleClientComm

    private void HandleClientComm(object client)
    {
        tcp_client = (TcpClient)client;
        NetworkStream client_stream = tcp_client.GetStream();

        byte[] message = new byte[2048];
        int bytes_read;

        while(isTrue == true)
        {
            bytes_read = 0;

            try
            {
                //blocks until a client sends a message
                bytes_read = client_stream.Read(message, 0, 2048);
                //Debug.Log(message);

            }
            catch (Exception e)
            {
                //a socket error has occured
                Debug.Log(e.Message);
                break;
            }

            if(bytes_read == 0)
            {
                //client has disconnected
                Debug.Log("Disconnected");
                tcp_client.Close();
                break;
            }

            ASCIIEncoding encoder = new ASCIIEncoding();
            String msg = encoder.GetString(message,0,bytes_read);
            //Debug.Log(msg);
            String[] nums = msg.Split('!');
            float x,y,z;
            if (nums.Length==3) {
                x = float.Parse(nums[0], CultureInfo.InvariantCulture.NumberFormat);
                y = float.Parse(nums[1], CultureInfo.InvariantCulture.NumberFormat);
                z = float.Parse(nums[2], CultureInfo.InvariantCulture.NumberFormat);
                Vector3 newPos = new Vector3(x,y,z);
                player.changePos(newPos);
            }
            else {
                tcp_client.GetStream().Close();
                tcp_client.Close();
            }

        }

        if(isTrue == false)
        {
            tcp_client.Close();
            Debug.Log("closing tcp client");
        }
    }
开发者ID:lcsmedina,项目名称:HeadTrackingGame2013,代码行数:59,代码来源:TCP.cs

示例2: getHLogin

    public void getHLogin(string[] reqs)
    {
        string users = "";
        if (reqs.Length == 1) {
            users = uname;
        } else {
            if (reqs[1].EndsWith(":")) {
                streamW.WriteLine("401 Fail: Bad Request.");
                return;
            }
            users = reqs[1];
        }
        ArrayList responses = new ArrayList();
        TcpClient c = new TcpClient();
        for (int i = 0; i < GameMatchingServer.knownServers.Count; i++) {
            Server s = (Server) GameMatchingServer.knownServers[i];
            try {
                c = new TcpClient();
                c.Connect(s.IP, s.port);

                Stream str = c.GetStream();
                StreamWriter strW = new StreamWriter(str);
                StreamReader strR = new StreamReader(str);
                strW.AutoFlush = true;

                // Login as ourselves.
                strW.WriteLine("SERVER {0}:{1}", GameMatchingServer.port,
                        GameMatchingServer.nickName);

                // reads first 200 and 200 after SERVER command.
                strR.ReadLine();
                string TwoHundredTest = strR.ReadLine();
                if (TwoHundredTest.StartsWith("100")) {
                    strR.ReadLine();
                }

                strW.WriteLine("GETH {0}", users);

                string first = strR.ReadLine();

                int k = 0;
                while (first.StartsWith("-200")) {
                    responses.Add(first);
                    k++;
                    first = strR.ReadLine();
                }
                str.Close();
                c.Close();

            } catch (Exception) {
                c.Close();
            }
        }

        for (int i = 0; i < responses.Count; i++) {
            streamW.WriteLine((string)responses[i]);
        }
        streamW.WriteLine("200 {0}:There are {0} matches in the results", responses.Count);
    }
开发者ID:richmt,项目名称:gameMatchingServer,代码行数:59,代码来源:ClientRequest_LoginReqs.cs

示例3: Main

    public static void Main()
    {
        TcpClient tcpClient = new TcpClient();
                try{
                        tcpClient.Connect("localhost", portNum);
                        NetworkStream networkStream = tcpClient.GetStream();

                        if (networkStream.CanWrite && networkStream.CanRead){

                                String DataToSend = "" ;

                                while ( DataToSend != "quit" ) {

                                            Console.WriteLine("\nType a text to be sent:");
            DataToSend = Console.ReadLine() ;
            if ( DataToSend.Length == 0 ) break ;

                                            Byte[] sendBytes = Encoding.ASCII.GetBytes(DataToSend);
                                            networkStream.Write(sendBytes, 0, sendBytes.Length);

                                            // Reads the NetworkStream into a byte buffer.
                                            byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
                                            int BytesRead = networkStream.Read(bytes, 0, (int) tcpClient.ReceiveBufferSize);

                                            // Returns the data received from the host to the console.
                                            string returndata = Encoding.ASCII.GetString(bytes, 0 , BytesRead);
                                            Console.WriteLine("This is what the host returned to you: \r\n{0}", returndata);
                                }
                                networkStream.Close();
                                tcpClient.Close();
                        }
                        else if (!networkStream.CanRead){
                                Console.WriteLine("You can not write data to this stream");
                              tcpClient.Close();
                        }
                        else if (!networkStream.CanWrite){
                              Console.WriteLine("You can not read data from this stream");
                              tcpClient.Close();
                        }
                }
               catch (SocketException) {
                        Console.WriteLine("Sever not available!");
               }
               catch (System.IO.IOException) {
                       Console.WriteLine("Sever not available!");
               }
               catch (Exception e ) {
                        Console.WriteLine(e.ToString());
                }
    }
开发者ID:randoro,项目名称:Gridrift,代码行数:50,代码来源:TcpClientTest.cs

示例4: TryConnect

    //пытаемся отправить кому-то сообщение о том, что хотим понаблюдать за его игрой
    //если прокатывает - в ответ нам начнут приходить сообщения о состоянии игры
    public void TryConnect(string ip, string port)
    {
        try
        {
            TcpClient tcpclnt = new TcpClient();
            tcpclnt.Connect(IPAddress.Parse(ip), int.Parse(port));
            String str = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] ba = asen.GetBytes(str);
            stm.Write(ba, 0, ba.Length);
            byte[] bb = new byte[255];
            int k = stm.Read(bb, 0, 255);

            string an = "";
            for (int i = 0; i < k; i++)
                an += Convert.ToChar(bb[i]);

            stm.Close();
            tcpclnt.Close();
        }
        catch (Exception e)
        {
            Debug.LogError(e.StackTrace);
        }
    }
开发者ID:BoogieGo,项目名称:avegames_task,代码行数:29,代码来源:NetworkManager.cs

示例5: Main

 public static void Main(String [] args)
 {
     TcpClient client = new TcpClient(args[0], int.Parse(args[1]));
     NetworkStream stream = client.GetStream();
     byte[] send = Encoding.ASCII.GetBytes
                  ("GET " + args[2] + " HTTP/1.0 \r\n");
     stream.Write(send, 0, send.Length);
     send = Encoding.ASCII.GetBytes
           ("Host: " + args[0] + ':' + args[1] + "\r\n\r\n");
     stream.Write(send, 0, send.Length);
     int size = (int)client.ReceiveBufferSize;
     byte[] bytes = new byte[size];
     StreamReader reader = new StreamReader(stream);
     while(reader.ReadLine() != "");
     String s;
     try{
       while((s = reader.ReadLine()) != null)
      Console.WriteLine(s);
     }catch(IOException e) {
     }finally {
       reader.Close();
       stream.Close();
       client.Close();
     }
 }
开发者ID:JnS-Software-LLC,项目名称:CSC153,代码行数:25,代码来源:VerySimpleBrowser.cs

示例6: LEDSingleSwitch

    void LEDSingleSwitch()
    {
        //IPアドレスとポート番号を指定
        //string型とint型なのが不思議
        //勿論送信先のIPアドレスとポート番号です
        string ipAddress = "172.20.11.68";
        int port = 14649;

        //IPアドレスとポート番号を渡してサーバ側へ接続
        TcpClient client = new TcpClient(ipAddress, port);

        //表示するのは「Hello! C#」
        //これを送信用にbyte型へ直します

        string str = "SET_SINGLE " +number+ " " +single+ "," +single+ "," +single+ "," +single+ ",\nUPDATE\nUPDATE\n";
        byte[] tmp = Encoding.UTF8.GetBytes(str);

        //NWのデータを扱うストリームを作成
        NetworkStream stream = client.GetStream();

        //送信
        //引数は(データ , データ書き込み開始位置 , 書き込むバイト数)
        //だそうです
        stream.Write(tmp, 0, tmp.Length);

        //サーバとの接続を終了
        client.Close();
    }
开发者ID:kentx422,项目名称:Unity_BackUp,代码行数:28,代码来源:easyLux.cs

示例7: Main

        static void Main(string[] args)
        {
            Console.Write("IP: ");
            IPAddress ip = IPAddress.Parse(Console.ReadLine());
            Console.Write("Slóð: ");
            string slod = Console.ReadLine();

            try
            {
                TcpClient client = new TcpClient();
                client.Connect(new IPEndPoint(ip, 1337));
                NetworkStream s = client.GetStream();

                StreamWriter sw = new StreamWriter(s);
                sw.WriteLine(slod);
                sw.Flush();

                StreamReader sr = new StreamReader(s);
                Console.WriteLine(sr.ReadLine());

                s.Close();
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Villa!");
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            Console.ReadLine();
        }
开发者ID:SuprDewd,项目名称:Forritunarkeppnin-2,代码行数:32,代码来源:Program.cs

示例8: Main

    static void Main(string[] args)
    {
        if (args.Length != 2) // Test for correct # of args
          throw new ArgumentException("Parameters: <Destination> <Port>");

        String server = args[0];             // Destination address
        int servPort = Int32.Parse(args[1]); // Destination port

        // Create socket that is connected to server on specified port
        TcpClient client = new TcpClient(server, servPort);
        NetworkStream netStream = client.GetStream();

        ItemQuote quote = new ItemQuote(1234567890987654L, "5mm Super Widgets",
                                    1000, 12999, true, false);

        // Send text-encoded quote
        ItemQuoteEncoderText coder = new ItemQuoteEncoderText();
        byte[] codedQuote = coder.encode(quote);
        Console.WriteLine("Sending Text-Encoded Quote (" +
                      codedQuote.Length + " bytes): ");
        Console.WriteLine(quote);

        netStream.Write(codedQuote, 0, codedQuote.Length);

        // Receive binary-encoded quote
        ItemQuoteDecoder decoder = new ItemQuoteDecoderBin();
        ItemQuote receivedQuote = decoder.decode(client.GetStream());
        Console.WriteLine("Received Binary-Encode Quote:");
        Console.WriteLine(receivedQuote);

        netStream.Close();
        client.Close();
    }
开发者ID:jin55132,项目名称:TCPCSharp,代码行数:33,代码来源:SendTcp.cs

示例9: btnReadScale_Click

 protected void btnReadScale_Click(object sender, EventArgs e)
 {
     string weight;
     try
     {
         Int32 port = 1365;
         TcpClient client = new TcpClient("10.3.109.247", port);
         Byte[] data = System.Text.Encoding.ASCII.GetBytes("%q");
         NetworkStream stream = client.GetStream();
         stream.Write(data, 0, data.Length);
         data = new Byte[256];
         String responseData = String.Empty;
         Int32 bytes = stream.Read(data, 0, data.Length);
         responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
         stream.Close();
         client.Close();
         weight = responseData.Substring(5).Replace(",", ".").Replace("+", "").Replace("!", "");
         //weight = responseData.Substring(6).Replace(",", ".");
         txtBoxWeight.Text = weight;
         Session["SE_weight"] = weight;
     }
     catch (ArgumentNullException ex)
     {
         Debug.WriteLine("ArgumentNullException: {0}", e);
     }
     catch (SocketException ex)
     {
         Debug.WriteLine("SocketException: {0}", e);
     }
 }
开发者ID:r1chjames,项目名称:CSEBSFrontEnd,代码行数:30,代码来源:Goods_In_2.aspx.cs

示例10: Main

	public static void Main() {
		
		try {
			TcpClient tcpclnt = new TcpClient();
			Console.WriteLine("Connecting.....");
			
			tcpclnt.Connect("172.21.5.99",8001); // use the ipaddress as in the server program
			
			Console.WriteLine("Connected");
			Console.Write("Enter the string to be transmitted : ");
			
			String str=Console.ReadLine();
			Stream stm = tcpclnt.GetStream();
						
			ASCIIEncoding asen= new ASCIIEncoding();
			byte[] ba=asen.GetBytes(str);
			Console.WriteLine("Transmitting.....");
			
			stm.Write(ba,0,ba.Length);
			
			byte[] bb=new byte[100];
			int k=stm.Read(bb,0,100);
			
			for (int i=0;i<k;i++)
				Console.Write(Convert.ToChar(bb[i]));
			
			tcpclnt.Close();
		}
		
		catch (Exception e) {
			Console.WriteLine("Error..... " + e.StackTrace);
		}
	}
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:33,代码来源:clnt.cs

示例11: sendPacket

 public string sendPacket(string packet)
 {
     try
     {
         TcpClient client = new TcpClient(ipAddress, port);
         Byte[] data = System.Text.Encoding.ASCII.GetBytes(packet);
         NetworkStream stream = client.GetStream();
         stream.Write(data, 0, data.Length);
         data = new Byte[256];
         String responseData = String.Empty;
         Int32 bytes = stream.Read(data, 0, data.Length);
         responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
         stream.Close();
         client.Close();
         return responseData;
     }
     catch (ArgumentNullException e)
     {
         return(e.ToString());
     }
     catch (SocketException e)
     {
         return (e.ToString());
     }
 }
开发者ID:cosmicpeanut,项目名称:ChatApplication,代码行数:25,代码来源:Packet.cs

示例12: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //создание экземпляра класса IPEndPoint
                IPEndPoint endPoint = new IPEndPoint(
                    IPAddress.Parse(textBox1.Text),
                    Convert.ToInt32(textBox3.Text)
                );
                client = new TcpClient();
                //установка соединения с использованием 
                //данных IP и номера порта
                client.Connect(endPoint);

                //получение сетевого потока
                NetworkStream nstream = client.GetStream();
                //преобразование строки сообщения в массив байт
                byte[] barray = Encoding.Unicode.GetBytes(textBox2.Text);
                //запись в сетевой поток всего массива 
                nstream.Write(barray, 0, barray.Length);
                //закрытие клиента
                client.Close();
            }
            catch (SocketException sockEx)
            {
                MessageBox.Show("Ошибка сокета:" + sockEx.Message);
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Ошибка :" + Ex.Message);
            }
        }
开发者ID:xs2ranjeet,项目名称:13ns9-1spr,代码行数:32,代码来源:Form1.cs

示例13: StartAttend

    private static async void StartAttend(int sessionId, TcpClient session)
    {
        Console.WriteLine("++ [S{0}:T{1}] connection from {2}",
            sessionId,
            Thread.CurrentThread.ManagedThreadId,
            session.Client.RemoteEndPoint
        );
        NetworkStream stream = session.GetStream();

        int nb;
        byte[] buffer = new byte[8];

		for (;;) {
            nb = await stream.ReadAsync(buffer, 0, buffer.Length);

            if (nb == 0) {
                Console.WriteLine("++ [S{0}:T{1}] end of session",
                    sessionId,
                    Thread.CurrentThread.ManagedThreadId
                );
                session.Close();
                return;
            }

            Console.WriteLine("++ [S{0}:T{1}] processing {2} byte(s)",
                sessionId,
                Thread.CurrentThread.ManagedThreadId,
                nb
            );

            Pause(500);

            stream.Write(buffer, 0, nb);
        }
    }
开发者ID:Skyish,项目名称:isel-pc-1516-1,代码行数:35,代码来源:EchoServer4_AsyncAwait.cs

示例14: Connect

	public static TcpClient Connect( string ip, ushort port, int timeoutMSec)
	{
		TimeoutObject.Reset(); // 이벤트 상태를 초기화

		socketexception = null; // 예외발생

		string serverip = ip; // IP

		int serverport = port;

		TcpClient tcpclient = new TcpClient();

		// 비동기 접속, CallBackMethod

		tcpclient.BeginConnect( serverip, serverport, new AsyncCallback( CallBackMethod), tcpclient);

		if ( TimeoutObject.WaitOne( timeoutMSec, false)) // 동기화시킨다. timeoutMSec 동안 기다린다.
		{
			if ( IsConnectionSuccessful) // 접속되는 소켓을
				return tcpclient;
			else
				throw socketexception; // 안되면, 안된 예외를
		}
		else // 시간이 초과되면
		{
			tcpclient.Close();
			throw new TimeoutException( "TimeOut Exception");
		}
	}
开发者ID:ftcaicai,项目名称:ArkClient,代码行数:29,代码来源:AsTimeoutSocket.cs

示例15: Main

    static void Main(string[] args)
    {
        try {
            client = new TcpClient("127.0.0.1", 7777);
            ins = new StreamReader(client.GetStream());
            ots = new StreamWriter(client.GetStream());
            ots.AutoFlush = true;
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        if (client != null && ots != null && ins != null) {
            try {
                cThread cli = new cThread(client, ins, ots);
                Thread ctThread = new Thread(cli.run);
                ctThread.Start();

                while (!cli.closed) {
                    string msg = Console.ReadLine().Trim();
                    ots.WriteLine(msg);
                }
                ots.Close();
                ins.Close();
                client.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
    }
开发者ID:Cotel,项目名称:MultiThread-Chat,代码行数:29,代码来源:Cliente.cs


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