DotNet · 2011年3月18日

TcpClient类的一般用法

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8.   
  9. using System.Net;  
  10. using System.Net.Sockets;  
  11.   
  12. namespace WinNet  
  13. {  
  14.     public partial class ClientFrm : Form  
  15.     {  
  16.         public ClientFrm()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.   
  21.         private void ClientFrm_Load(object sender, EventArgs e)  
  22.         {  
  23.             //这就是服务器与客户端的一条通讯线路  
  24.             TcpClient tcpClient = new TcpClient();  
  25.             //得到服务器端IP,然后建立一个连接  
  26.             IPHostEntry host = Dns.GetHostEntry(“127.0.0.1”);  
  27.             tcpClient.Connect(host.AddressList[0], 8888);  
  28.             //取得数据流  
  29.             NetworkStream clientStream = tcpClient.GetStream();  
  30.             //只能向服务器发送字节流,所以要编码  
  31.             byte[] response = new byte[10];  
  32.             response = System.Text.Encoding.ASCII.GetBytes(“helloserve”.ToCharArray());  
  33.             //通过Write方法把客户端数据发向服务器  
  34.             clientStream.Write(response, 0, 10);  
  35.             //通过Read方法读取服务器端发过来的数据  
  36.             clientStream.Read(response, 0, 10);  
  37.             this.Text = System.Text.Encoding.ASCII.GetString(response);  
  38.   
  39.             tcpClient.Close();  
  40.             clientStream.Close();  
  41.         }  
  42.     }  
  43. }  

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞