在TcpClient上調用GetStream()方法來獲得串連到遠端電腦的流。注意這裡我用了遠程這個詞,當在用戶端調用時,它得到串連服務端的流;當在服務端調用時,它獲得串連用戶端的流。接下來我們來看一下代碼,我們先看服務端
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.Net.Sockets;namespace SocksTest{ class Program { static void Main(string[] args) { int BufferSize=1000; Console.WriteLine("Server is running ... "); IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 }); TcpListener listener = new TcpListener(ip, 8500); listener.Start(); // 開始偵聽 Console.WriteLine("Start Listening ..."); TcpClient remoteClient = listener.AcceptTcpClient();//接受掛起的串連請求 Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint.ToString(), remoteClient.Client.RemoteEndPoint.ToString()); NetworkStream streamClient = remoteClient.GetStream(); Byte[] buffer=new Byte[BufferSize]; int bytesRead = streamClient.Read(buffer, 0, BufferSize); Console.WriteLine("Reading data,{0} bytes...",bytesRead); string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received:{0}",msg); Console.Read(); } }}
streamClient.GetStream()方法擷取到了串連至用戶端的流,然後從流中讀出資料並儲存在了buffer緩衝中,隨後使用Encoding.Unicode.GetString()方法,從緩衝中擷取到了實際的字串。最後將字串列印在了控制台上。這段代碼有個地方需要注意:在能夠讀取的字串的總位元組數大於BufferSize的時候會出現字串截斷現象,因為緩衝中的數目總是有限的,而對於大對象,比如說圖片或者其它檔案來說,則必須採用“分次讀取然後轉存”這種方式
// 擷取字串byte[] buffer = new byte[BufferSize];int bytesRead; // 讀取的位元組數MemoryStream msStream = new MemoryStream();do { bytesRead = streamToClient.Read(buffer, 0, BufferSize); msStream.Write(buffer, 0, bytesRead);} while (bytesRead > 0);buffer = msStream.GetBuffer();string msg = Encoding.Unicode.GetString(buffer);
用戶端
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Sockets;namespace SocksClient{ class Program { static void Main(string[] args) { Console.WriteLine("Client is running......"); TcpClient tcpClient; try { tcpClient = new TcpClient(); tcpClient.Connect("localhost", 8500); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Read(); return; } Console.WriteLine("Server Connected!{0} --> {1}", tcpClient.Client.LocalEndPoint.ToString(), tcpClient.Client.RemoteEndPoint.ToString()); NetworkStream streamServer = tcpClient.GetStream(); string msg = "Hi server,this is from Client"; byte[] buffer=Encoding.Unicode.GetBytes(msg); streamServer.Write(buffer, 0, buffer.Length); Console.Read(); } }}
同樣的,和上篇的原理相同,如何?多用戶端與伺服器通訊等等,我這裡拋個磚,接下來由大家自己繼續深入了。
1. 單C<--->單S 通訊
2. 多C<--->單S 通訊
3. 單C多資訊<--->單S 通訊
4. 多C多資訊<--->單S 通訊