您好,登錄后才能下訂單哦!
在.NET技術大系當中,有很多服務編程的技術,比如socket、windows service、.net remoting、message queue、web service、wcf等等,這些技術都往往與網絡知識緊密相關,有時還會結合多線程等技術,實現特定的需求。這里只以Socket為例,看如何運用C#進行網絡編程。
熟悉Socket編程的應該都不陌生,要實現Socket,需要一個服務端程序以及一個客戶端程序,服務端程序綁定IP、Port,建立偵聽;客戶端程序建立連接,向服務端拋出請求,通過TCP或UDP協議,獲得服務端的反饋,這是一個雙工通信的過程。而且最重要的是,Socket通信與具體編程語言無關,C、C++、JAVA、C#、PHP、Flex等高級編程語言都提供了相應的實現。
下面這個是個客戶端Socket的簡單例子,也是實際工作中曾經用過的。當時的情況是Socket服務端是用Java開發的一個程序,通過使用Socket,讓兩臺不同網絡的的機器通過前置機獲取對方的信息。通過客戶端發起請求,服務端監聽收到請求后,進行響應處理,并把封裝好的XML文檔返回客戶端。客戶端收到XML數據后進行解析處理即可。
/// <summary> /// 獲取通訊中間件通過socket發送的數據,DataTable /// </summary> /// <param name="requestCode">請求code</param> /// <param name="array">查詢的條件,封裝在數組里</param> /// <param name="errMsg">錯誤提示</param> /// <returns>經過一系列處理過后的DataTable</returns> public DataTable GetDataTable(string requestCode, IList<string> list, out string errMsg) { try { string ip = ConfigurationManager.AppSettings["ip"].ToString().Trim();//中間件的ip地址 int port = Convert.ToInt32(ConfigurationManager.AppSettings["port"].ToString().Trim());//中間件的端口號 IPEndPoint serverip = new IPEndPoint(IPAddress.Parse(ip), port); using (Socket clientSocket = new Socket(serverip.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { clientSocket.Connect(serverip);//socket連接指定中間件前置機 string outBufferString = string.Empty;//準備發送的報文 switch (requestCode) { case "111001": outBufferString = PrepareSendPackets("111001", list); break; case "111002": outBufferString = PrepareSendPackets("111002", list); break; case "111003": outBufferString = PrepareSendPackets("111003", list); break; default: break; } byte[] outBuffer = new byte[2048]; outBuffer = Encoding.GetEncoding("gbk").GetBytes(outBufferString); clientSocket.Send(outBuffer, outBuffer.Length, 0);//發送報文 byte[] inBuffer = new byte[51200]; clientSocket.Receive(inBuffer, inBuffer.Length, 0);//接收報文 string inBufferString = "<?xml version='1.0' encoding='gb2312' ?> "; inBufferString += Encoding.GetEncoding("gbk").GetString(inBuffer); DataTable dt = ParsingPackets(requestCode, inBufferString, out errMsg); return dt; } } catch (Exception ex) { throw ex; } }
再附一個完整一點的小例子。
這個程序簡單實現了客戶端發送消息,服務端接收消息并反饋給客戶端消息的過程。用了同步模式,是最簡單的socket通信模型。
服務端控制臺:
static void Main(string[] args) { //定義一個字典用于存放用戶列表 Dictionary<string, string> users = new Dictionary<string, string>(); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("192.168.1.7"), 1234); socket.Bind(ipe); socket.Listen(10); Console.WriteLine("socket start!"); while (true)//服務端死循環,不斷提供socket服務 { Socket clientSocket = socket.Accept();//等待客戶端請求 IPEndPoint ip = (IPEndPoint)clientSocket.RemoteEndPoint; string remoteAddress = ip.Address.ToString();//遠程IP地址 byte[] revBytes = new byte[512]; clientSocket.Receive(revBytes);//接收客戶端發送的消息 string user = Encoding.Default.GetString(revBytes); if (!users.ContainsKey(remoteAddress)) { users.Add(remoteAddress, user); } Console.WriteLine("來自于" + remoteAddress + "的用戶:" + user); string content = "歡迎來到socket的世界!"; byte[] bytes = Encoding.Default.GetBytes(content); clientSocket.Send(bytes);//發送服務端消息到客戶端 clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } } }
客戶端WPF:
public MainWindow() { InitializeComponent(); } private string ip;//傳入的ip private string username;//傳入的用戶名 public MainWindow(string ip, string username) { InitializeComponent(); this.ip = ip; this.username = username; } private void button1_Click(object sender, RoutedEventArgs e) { SendSocketPackge(); } private static Socket client;//socket對象 /// <summary> /// 發送數據包 /// </summary> private void SendSocketPackge() { //建立1個Socket對象發起TCP連接 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(IPAddress.Parse("192.168.1.7"), 1234);//連接到服務器指定IP及Port string userSays = username + "說:" + this.textBox1.Text;//username自己用一個字符串代替 client.Send(Encoding.Default.GetBytes(userSays));//將當前的用戶名發送給服務器端 byte[] bytes = new byte[512]; client.Receive(bytes);//接收服務端發送的消息 client.Shutdown(SocketShutdown.Both); client.Close(); string content = string.Join(" ", DateTime.Now.ToString(), Encoding.Default.GetString(bytes)); listBox1.Items.Add(content);//將消息加載到listbox列表 } private void Window_Loaded(object sender, RoutedEventArgs e) { ip = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(); this.Title = "來自:" + ip + "的用戶:" + username; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (client != null && client.Connected) { client.Shutdown(SocketShutdown.Both); client.Close(); } }
效果圖:
服務啟動時:
客戶端界面:
點擊發送后,服務端顯示的消息:
由于代碼比較簡單,就不上傳項目文件了,這里簡單演示了一下C#Socket通信的核心代碼。讀者可以在此基礎上不斷擴展。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。