本篇文章主要實(shí)現(xiàn)Socket在Tcp\Udp協(xié)議下相互通訊的方式。(服務(wù)器端與客戶(hù)端的通訊) 1.基于Tcp協(xié)議的Socket通訊類(lèi)似于B/S架構(gòu),面向連接,但不同的是服務(wù)器端可以向客戶(hù)端主動(dòng)推送消息。 使用Tcp協(xié)議通訊需要具備以下幾個(gè)條件: (1).建立一個(gè)套接字(Socket) (2).綁定服務(wù)器端IP地址及端口號(hào)--服務(wù)器端 (3).利用Listen()方法開(kāi)啟監(jiān)聽(tīng)--服務(wù)器端 (4).利用Accept()方法嘗試與客戶(hù)端建立一個(gè)連接--服務(wù)器端 (5).利用Connect()方法與服務(wù)器建立連接--客戶(hù)端 (5).利用Send()方法向建立連接的主機(jī)發(fā)送消息 (6).利用Recive()方法接受來(lái)自建立連接的主機(jī)的消息(可靠連接)
2.基于Udp協(xié)議是無(wú)連接模式通訊,占用資源少,響應(yīng)速度快,延時(shí)低。至于可靠性,可通過(guò)應(yīng)用層的控制來(lái)滿足。(不可靠連接) (1).建立一個(gè)套接字(Socket) (2).綁定服務(wù)器端IP地址及端口號(hào)--服務(wù)器端 (3).通過(guò)SendTo()方法向指定主機(jī)發(fā)送消息(需提供主機(jī)IP地址及端口) (4).通過(guò)ReciveFrom()方法接收指定主機(jī)發(fā)送的消息(需提供主機(jī)IP地址及端口)
上代碼:由于個(gè)人代碼風(fēng)格,習(xí)慣性將兩種方式寫(xiě)在一起,讓用戶(hù)主動(dòng)選擇Tcp\Udp協(xié)議通訊 服務(wù)器端: using System; using System.Collections.Generic; using System.Text; #region 命名空間 using System.Net; using System.Net.Sockets; using System.Threading; #endregion namespace SocketServerConsole { class Program { #region 控制臺(tái)主函數(shù) /// <summary> /// 控制臺(tái)主函數(shù) /// </summary> /// <param name="args"></param> static void Main(string[] args) { //主機(jī)IP IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.105"), 8686); Console.WriteLine("請(qǐng)選擇連接方式:"); Console.WriteLine("A.Tcp"); Console.WriteLine("B.Udp"); ConsoleKey key; while (true) { key = Console.ReadKey(true).Key; if (key == ConsoleKey.A) TcpServer(serverIP); else if (key == ConsoleKey.B) UdpServer(serverIP); else { Console.WriteLine("輸入有誤,請(qǐng)重新輸入:"); continue; } break; } } #endregion #region Tcp連接方式 /// <summary> /// Tcp連接方式 /// </summary> /// <param name="serverIP"></param> public static void TcpServer(IPEndPoint serverIP) { Console.WriteLine("客戶(hù)端Tcp連接模式"); Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpServer.Bind(serverIP); tcpServer.Listen(100); Console.WriteLine("開(kāi)啟監(jiān)聽(tīng)..."); new Thread(() => { while (true) { try { TcpRecive(tcpServer.Accept()); } catch (Exception ex) { Console.WriteLine(string.Format("出現(xiàn)異常:{0}", ex.Message)); break; } } }).Start(); Console.WriteLine("\n\n輸入\"Q\"鍵退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); tcpServer.Close(); } public static void TcpRecive(Socket tcpClient) { new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = tcpClient.Receive(data); } catch (Exception ex) { Console.WriteLine(string.Format("出現(xiàn)異常:{0}", ex.Message)); break; } Console.WriteLine(string.Format("收到消息:{0}", Encoding.UTF8.GetString(data))); string sendMsg = "收到消息!"; tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg)); } }).Start(); } #endregion #region Udp連接方式 /// <summary> /// Udp連接方式 /// </summary> /// <param name="serverIP"></param> public static void UdpServer(IPEndPoint serverIP) { Console.WriteLine("客戶(hù)端Udp模式"); Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpServer.Bind(serverIP); IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)ipep; new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = udpServer.ReceiveFrom(data, ref Remote);//接受來(lái)自服務(wù)器的數(shù)據(jù) } catch (Exception ex) { Console.WriteLine(string.Format("出現(xiàn)異常:{0}", ex.Message)); break; } Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); string sendMsg = "收到消息!"; udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None, Remote); } }).Start(); Console.WriteLine("\n\n輸入\"Q\"鍵退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); udpServer.Close(); } #endregion } } 客戶(hù)端:
using System; using System.Collections.Generic; using System.Text; #region 命名空間 using System.Net.Sockets; using System.Net; using System.Threading; #endregion namespace SocketClientConsole { class Program { #region 控制臺(tái)主函數(shù) /// <summary> /// 控制臺(tái)主函數(shù) /// </summary> /// <param name="args"></param> static void Main(string[] args) { //主機(jī)IP IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.77"), 8686); Console.WriteLine("請(qǐng)選擇連接方式:"); Console.WriteLine("A.Tcp"); Console.WriteLine("B.Udp"); ConsoleKey key; while (true) { key = Console.ReadKey(true).Key; if (key == ConsoleKey.A) TcpServer(serverIP); else if (key == ConsoleKey.B) UdpClient(serverIP); else { Console.WriteLine("輸入有誤,請(qǐng)重新輸入:"); continue; } break; } } #endregion #region Tcp連接方式 /// <summary> /// Tcp連接方式 /// </summary> /// <param name="serverIP"></param> public static void TcpServer(IPEndPoint serverIP) { Console.WriteLine("客戶(hù)端Tcp連接模式"); Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { tcpClient.Connect(serverIP); } catch (SocketException e) { Console.WriteLine(string.Format("連接出錯(cuò):{0}", e.Message)); Console.WriteLine("點(diǎn)擊任何鍵退出!"); Console.ReadKey(); return; } Console.WriteLine("客戶(hù)端:client-->server"); string message = "我上線了..."; tcpClient.Send(Encoding.UTF8.GetBytes(message)); Console.WriteLine(string.Format("發(fā)送消息:{0}", message)); new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = tcpClient.Receive(data); } catch (Exception ex) { Console.WriteLine(string.Format("出現(xiàn)異常:{0}", ex.Message)); break; } Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); } }).Start(); Console.WriteLine("\n\n輸入\"Q\"鍵退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); tcpClient.Close(); } #endregion #region Udp連接方式 /// <summary> /// Udp連接方式 /// </summary> /// <param name="serverIP"></param> public static void UdpClient(IPEndPoint serverIP) { Console.WriteLine("客戶(hù)端Udp模式"); Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string message = "我上線了..."; udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP); Console.WriteLine(string.Format("發(fā)送消息:{0}", message)); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = udpClient.ReceiveFrom(data, ref Remote);//接受來(lái)自服務(wù)器的數(shù)據(jù) } catch (Exception ex) { Console.WriteLine(string.Format("出現(xiàn)異常:{0}", ex.Message)); break; } Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); } }).Start(); Console.WriteLine("\n\n輸入\"Q\"鍵退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); udpClient.Close(); } #endregion } } Tcp協(xié)議下通訊效果如下圖: 客戶(hù)端:
服務(wù)器端:
基于Udp協(xié)議下通訊效果如下圖: 客戶(hù)端:
服務(wù)器端:
總結(jié):Tcp協(xié)議相對(duì)通訊來(lái)說(shuō)相對(duì)可靠,信息不易丟失,Tcp協(xié)議發(fā)送消息,發(fā)送失敗時(shí)會(huì)重復(fù)發(fā)送消息等原因。所以對(duì)于要求通訊安全較高的程序來(lái)說(shuō),選擇Tcp協(xié)議的通訊相對(duì)合適。Upd協(xié)議通訊個(gè)人是比較推薦的,占用資源小,低延時(shí),響應(yīng)速度快。至于可靠性是可以通過(guò)一些應(yīng)用層加以封裝控制得到相應(yīng)的滿足。
附上源碼:Socket-Part1.zip 作者:曾慶雷 出處:http://www.cnblogs.com/zengqinglei 本頁(yè)版權(quán)歸作者和博客園所有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明, 且在文章頁(yè)面明顯位置給出原文鏈接,否則保留追究法律責(zé)任的權(quán)利 |
|