.NET ez 2012-06-04
TCP(Transmission Control Protocol)
UDP(User Datagram Protocol)
TCP這個協定最主要的特色在於傳輸資料時,需要驗證資 料,確保正確性。所以花的時間稍多一點。
而UDP這個協定最主要的特色在於傳輸資料時,不需要驗 證資料,不保證正確性,所以比較省時間。
而一般來說, 像是多媒體串流(streaming)就是使用這種協定。
Server端
using System; using System.Net; using System.Net.Sockets; using System.Text; public class UdpServer { public static void Main() { IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8888); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); while(true) { byte[] data = new byte[1024]; int recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv)); } } }
Client端
using System; using System.Net; using System.Net.Sockets; using System.Text; public class UdpClient { public static void Main(string[] args) { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("server ip"), 8888); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); while(true) { string input = Console.ReadLine(); if (input == "exit") break; server.SendTo(Encoding.UTF8.GetBytes(input), ipep); } Console.WriteLine("Stopping client"); server.Close(); } }
標籤: .NET