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


C# TcpClient.GetStream方法代码示例

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


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

示例1: ClientHandler

    public static void ClientHandler(TcpClient client) {
        var d = new Dictionary<string, ProcessCommand>() {
            { "cat", CatFile },
            { "clx", CalcClx },
            { "erf", CalcErf },
            { "sz", FileSize },
            { "info", GetInfo }
        };

        while (client.Connected) {
            using (var streamReader = new StreamReader(client.GetStream()))
            using (var streamWriter = new StreamWriter(client.GetStream())) {
                var cmd = streamReader.ReadLine().Split(" ".ToCharArray(), 2);

                try {
                    d[cmd[0]](cmd[1], streamWriter);
                }
                catch {
                    streamWriter.WriteLine("Error :(");
                }
                streamWriter.Flush();
            }
        }
        client.Close();
    }
开发者ID:noscripter,项目名称:root-2015-tasks,代码行数:25,代码来源:Program.cs

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

示例3: IrcClient

    /// <summary>
    /// 
    /// </summary>
    /// <param name="ip">irc.twitch.tv</param>
    /// <param name="port">6667</param>
    /// <param name="username">twitch username</param>
    /// <param name="password">must include the "oauth:" part</param>
    public IrcClient(string ip, int port, string username, string password)
    {
        this.username = username;
        tcpClient = new TcpClient(ip, port);
        input = new StreamReader(tcpClient.GetStream());
        output = new StreamWriter(tcpClient.GetStream()) { NewLine = "\r\n" };

        if (!password.StartsWith("oauth:"))
        {
            password = "oauth:" + password;
        }

        output.WriteLine("PASS " + password);
        output.WriteLine("NICK " + username);
        output.WriteLine("USER " + username + " 8 * :" + username);
        output.Flush();

        string message = ReadChatMessage();
        if (message.Contains("Error"))
        {
            int indexOfSep = message.LastIndexOf(':');
            if (indexOfSep >= 0)
            {
                message = message.Substring(indexOfSep + 1);
            }
            throw new Exception(message);
        }
    }
开发者ID:BallisticFrogs,项目名称:voodoochat,代码行数:35,代码来源:IrcClient.cs

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

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

示例6: fnConnectResult

 public string fnConnectResult(string sNetIP, int iPORT_NUM,string sUserName)
 {
     try
     {
         // GET LOCAL IP ADDRESS
         /*
         string strHostName = "";
         strHostName = System.Net.Dns.GetHostName();
         IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
         IPAddress[] addr = ipEntry.AddressList;
         Debug.Log( addr[addr.Length-1].ToString() );
         sNetIP = addr[addr.Length-1].ToString();
         */
         sNetIP = "localhost";
         // SET UP NEW TCP CLIENT AND CONNECT
         client = new TcpClient(sNetIP, PORT_NUM);
         client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
         Debug.Log("Connection Succeeded");
         //SendData("test");
         return "Connection Succeeded";
     }
     catch(Exception ex)
     {
         return "Server is not active.  Please start server and try again.      " + ex.ToString();
     }
 }
开发者ID:SLIPD,项目名称:PC,代码行数:26,代码来源:NetworkUDP.cs

示例7: Initialize

    public override void Initialize(IEventSource eventSource)
    {      
        try
        {
            this.InitializeParameters();
 
            this.SubscribeToEvents(eventSource);
 
            log.Info("Initialize MS Build Logger!");
 
            string ipStr = GetParameterValue("ip");
            IPAddress ipServer = IPAddress.Parse(ipStr);
            int port = int.Parse(GetParameterValue("port"));
            log.InfoFormat("MS Build Logger port to write {0}", port);
 
            clientSocketWriter = new System.Net.Sockets.TcpClient();
            clientSocketWriter.Connect(ipServer, port);
            networkStream = clientSocketWriter.GetStream();
            Thread.Sleep(1000);
        }
        catch(Exception ex)
        {
            log.Error("Exception in MS Build logger", ex);
        }    
    }  
开发者ID:kennedykinyanjui,项目名称:Projects,代码行数:25,代码来源:TcpIpLogger.cs

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

示例9: Connect_DnsEndPoint_Success

        public async Task Connect_DnsEndPoint_Success(int mode)
        {
            using (TcpClient client = new TcpClient())
            {
                Assert.False(client.Connected);

                string host = HttpTestServers.Host;
                const int port = 80;

                if (mode == 0)
                {
                    await client.ConnectAsync(host, port);
                }
                else
                {
                    IPAddress[] addresses = await Dns.GetHostAddressesAsync(host);
                    await (mode == 1 ?
                        client.ConnectAsync(addresses[0], port) :
                        client.ConnectAsync(addresses, port));
                }

                Assert.True(client.Connected);
                Assert.NotNull(client.Client);
                Assert.Same(client.Client, client.Client);

                using (NetworkStream s = client.GetStream())
                {
                    byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n");
                    await s.WriteAsync(getRequest, 0, getRequest.Length);
                    Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back
                }
            }
        }
开发者ID:rahulkotecha,项目名称:corefx,代码行数:33,代码来源:TcpClientTest.cs

示例10: StartTCPClient

    void StartTCPClient()
    {
        var host = serverUrl;
        var port = 5005;
        TcpClient tcpClient = new TcpClient(host, port);

        NetworkStream networkStream = tcpClient.GetStream();
        while (true) {
            if (networkStream.CanRead) {
                // Buffer to store the response bytes.
                byte[] readBuffer = new byte[tcpClient.ReceiveBufferSize];
                string fullServerReply = null;
                using (var writer = new MemoryStream()) {
                    do {
                        int numberOfBytesRead = networkStream.Read (readBuffer, 0, readBuffer.Length);
                        if (numberOfBytesRead <= 0) {
                            continue;
                        }
                        writer.Write (readBuffer, 0, numberOfBytesRead);
                    } while (networkStream.DataAvailable);
                    fullServerReply = Encoding.UTF8.GetString (writer.ToArray ());
                    var jsons = fullServerReply.Split(new string[] { "}{" }, StringSplitOptions.None);
                    foreach( var json in jsons){
                        var jsonData = json;
                        if (!json.EndsWith("}")){
                            jsonData = json + "}";
                        }
                        NewGloveData(jsonData);
                    }
                }
            }
        }
    }
开发者ID:mikahama,项目名称:RoomEscape,代码行数:33,代码来源:TCP_connector.cs

示例11: Connect

 void Connect()
 {
     try
     {
         client = new TcpClient(serverIP, port);
         stream = client.GetStream();
         Byte[] rMsg = System.Text.Encoding.ASCII.GetBytes(makeServerRegisterMessage());
         stream.Write(rMsg, 0, rMsg.Length);
         // Buffer to store the response bytes.
         rMsg = new Byte[BUFF_SIZE];
         // String to store the response ASCII representation.
         String responseData = String.Empty;
         // Read the first batch of the TcpServer response bytes.
         Int32 bytes = stream.Read(rMsg, 0, rMsg.Length);
         responseData = System.Text.Encoding.ASCII.GetString(rMsg, 0, bytes);
         //Debug.Log("bot server said : " + responseData);
     }
     catch (ArgumentNullException e)
     {
         Debug.LogError("ArgumentNullException: " + e);
     }
     catch (SocketException e)
     {
         Debug.LogError("SocketException: " + e.ToString());
     }
 }
开发者ID:Ooya,项目名称:Robot-Sapiens,代码行数:26,代码来源:botControl.cs

示例12: Connect

    public void Connect()
    {
        if (connected)
            return;

        username = usernameField.text.ToLower();
        oauthToken = oauthField.text;
        channel = "#" + username;
        if (username == "")
        {
            errorMessage.text = "please enter a username";
            return;
        }
        if(oauthToken == "")
        {
            errorMessage.text = "please enter your oauth token";
            return;
        }

        try
        {
            tcpClient = new TcpClient(SERVER, PORT);
        }
        catch (SocketException e)
        {
            errorMessage.text = "network error: " + e.Message;
        }
        nStream = tcpClient.GetStream();
        sReader = new StreamReader(nStream);
        sWriter = new StreamWriter(nStream);

        Write("USER " + username + "tmi twitch :" + username);
        Write("PASS " + oauthToken);
        Write("NICK " + username);
    }
开发者ID:CryptArc,项目名称:ScoreBall,代码行数:35,代码来源:TwitchInterface.cs

示例13: Connect

	public void Connect(){
		TcpClient client;
		YourName = InputName.GetComponent<InputField> ().text.Replace (" ", "_");
		if (YourName.Length == 0) {
			YourName = "Player";
		}
		try{
			String[] ip = InputIP.GetComponent<InputField> ().text.Split(':');
			client = new TcpClient(ip[0], Int32.Parse(ip[1]));
			Stream s = client.GetStream();
			sr = new StreamReader(s);
			sw = new StreamWriter(s);
			sw.AutoFlush = true;
			sw.WriteLine("READY " + YourName);

			new Thread(() => {
				while(client.Connected){
					String str = sr.ReadLine();
					msgs.Enqueue(str);
				}
			}).Start();

			ControlPanel.SetActive(true);
			ConnectPanel.SetActive(false);
		}catch(IndexOutOfRangeException){
			ShowPopup ("Wrong IP address. (IP_address:port)"); 
		}catch(Exception e){
			ShowPopup ("Cannot connect to server: " + e.Message);
		}
	}
开发者ID:0xE282B0,项目名称:poker,代码行数:30,代码来源:GameManager.cs

示例14: Initialize

    public static bool Initialize(string ip)
    {
        bool connection_failure = false;

        if(client != null)
        {
            receive_thread.Abort();
            send_thread.Abort();
            sreader.Close();
            swriter.Close();

        }

        client = new TcpClient();
        client.Connect(ip, port);
        var stream = client.GetStream();

        swriter = new StreamWriter(stream);
        sreader = new StreamReader(stream);

        receive_thread = new Thread(new ThreadStart(Receiver));
        receive_thread.Start();

        send_thread = new Thread(new ThreadStart(Sender));
        send_thread.Start();

        return connection_failure;
    }
开发者ID:JessicaMaxey,项目名称:Networks,代码行数:28,代码来源:NetworkController.cs

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


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