1、服務器端程序
可以在TcpClient上調用GetStream()方法來獲的鏈接到遠程計算機的網絡流NetworkStream。當在客戶端調用時,他獲的鏈接服務器端的流;當在服務器端調用時,他獲得鏈接客戶端的流。
class Program { static void Main(string[] args) { const int BufferSize = 8192;//緩存大小 Console.WriteLine("server is running ..."); IPAddress ip = new IPAddress(new byte[] { 192, 168, 1, 102 });//IP TcpListener listener = new TcpListener(ip, 8500); listener.Start();//開始偵聽 Console.WriteLine("start listener ..."); //獲取一個鏈接中斷方法 TcpClient remoteclient = listener.AcceptTcpClient(); //打印鏈接到客戶端的信息 Console.WriteLine("client connected ! Local:{0}<-- Client:{1}", remoteclient.Client.LocalEndPoint, remoteclient.Client.RemoteEndPoint); //獲取流,並寫入Buffer中 NetworkStream streamToClient = remoteclient.GetStream(); byte[] buffer = new byte[BufferSize]; int bytesRead = streamToClient.Read(buffer, 0, BufferSize); //獲得請求字符串 string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received:{0}[{1}bytes]", msg, bytesRead); Console.WriteLine("\n\n輸入\"Q\"鍵退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); } } View Code
如果傳遞的數據字節比較大,如圖片、音頻等,則采用“分次讀取然後轉存”的方式,代碼如下:
//獲取字符串 byte [] buffer = new byte[BufferSize]; int bytesRead; //讀取的字節數 MemoryStream ms =new MemoryStream(); do{ bytesRead = streamToClient.Read(buffer,0,BufferSize); ms.Write(buffer,0,bytesRead); }while(bytesRead > 0); buffer = msStream.GetBuffer(); string msg = Encoding.Unicode.GetString(buffer); View Code
2、客戶端程序
客戶端向服務器發送字符串的代碼與服務器端類似,先獲取鏈接服務器端的流,將字符串保存到buffer緩存中,再寫入流,寫入流的過程就相當於將消息發送到服務器端。
class Program { static void Main(string[] args) { Console.WriteLine("client is running ..."); TcpClient clint; try { clint = new TcpClient(); //與服務器建立連接 clint.Connect(IPAddress.Parse("192.168.1.102"), 8500); } catch (Exception ex) { Console.WriteLine(ex.Message); return; } //打印連接到服務器端的信息 Console.WriteLine("client connected ! Local:{0}<-- Client:{1}", clint.Client.LocalEndPoint, clint.Client.RemoteEndPoint); //要發送的信息 string msg = "hello"; NetworkStream streamToServer = clint.GetStream(); //獲取緩存 byte[] buffer = Encoding.Unicode.GetBytes(msg); //發送 streamToServer.Write(buffer, 0, buffer.Length); Console.WriteLine("Sent:{0}", msg); Console.WriteLine("\n\n輸入\"Q\"鍵退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); } } View Code
這樣就可以成功的發送和接收一個字符串了,如果想完成一些復雜的不間斷的交互就需要自己做一些調整了。