C#網路編程.2.通訊端.TcpListener.TcpClient.服務端用戶端通訊

來源:互聯網
上載者:User

在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 通訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.