C#網路程式設計指導?

C# 是一門網路程式語言,用它可進行有關網路的程式設計,如進行TCP程式設計、UDP程式設計、FTP程式設計、電子郵件程式設計、一些不需要流量的聊天工具等。

工具/原料

安裝有vs2008的計算機或者安裝有SharpDevelop_3.1.0.4977_Setup的計算機

方法/步驟

首先開啟SharpDevelop_3.1.0.4977_Setup

C#網路程式設計指導

網路程式設計指導#

然後點選【檔案】—【新建】—【解決方案】

C#網路程式設計指導

網路程式設計指導#

選擇控制檯程式,在下面的名稱中填寫程式的名字(可隨便給程式起個名字,但是首字必須是字母)

C#網路程式設計指導

網路程式設計指導#

最後點選【建立】

C#網路程式設計指導

網路程式設計指導#

下面是利用UdpClient編寫一個控制檯網路聊天工具(不需要連網通訊雙方就可以聊天)的相關程式碼:編寫【伺服器程式碼】如下:

using System; using System.Net; using System.Net.Sockets; using System.Text ; namespace server { class Program { public static void Main(string[] args) { // TODO: Implement Functionality Here UdpClient sc=new UdpClient (5050); Console.WriteLine ("waiting for a client...."); byte[] data = new byte[1024]; IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); while (true ) { data =sc.Receive (ref sender ); string s=Encoding.Unicode .GetString (data ); Console.WriteLine("Message received from {0}:{1}", sender.ToString(),s); if (s.Equals ("exit")) { break ; } string input; Console.Write ("input a string to send :"); input =Console.ReadLine (); data =Encoding.Unicode.GetBytes (input); sc.Send (data,data.Length ,sender ); } sc.Close (); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } }

編寫【客戶機程式碼】如下:

using System; using System.Net; using System.Net.Sockets; using System.Text ; namespace client { class Program { public static void Main(string[] args) { // TODO: Implement Functionality Here UdpClient sendclient=new UdpClient (0); IPEndPoint remoteEP=new IPEndPoint (IPAddress.Any ,0); byte[] recbuf; while (true ) { Console.Write("input a string to send (exit to exit):"); string tosend=Console.ReadLine (); byte [] b=Encoding.Unicode.GetBytes (tosend ); sendclient.Send (b,b.Length ,new IPEndPoint (IPAddress .Parse ("127.0.0.1"),5050)); if (tosend.Equals ("exit")) { break; } recbuf =sendclient.Receive (ref remoteEP); string ss=Encoding.Unicode.GetString (recbuf ); Console.WriteLine ("receive from {0}:{1}",remoteEP.ToString (),ss); if (ss.Equals ("exit")) { break; } } Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } }

編譯成功後的聊天頁面(本人試了一下,如下圖)

C#網路程式設計指導

網路程式設計指導#

注意事項

程式執行過程:先執行伺服器,再執行客戶機,雙方可互相輸入字串聊天,exit退出!

編譯成功後,客戶機先發一條訊息,伺服器接收成功後可進行回覆,每次只能發一條訊息(也就是說只能等對方回覆後,才可以發下一條訊息 !)

網路, 流量, 電子郵件, 聊天工具, 程式語言,
相關問題答案