TCP與UDP區別html
TCP---傳輸控制協議,提供的是面向鏈接、可靠的字節流服務。當客戶和服務器彼此交換數據前,必須先在雙方之間創建一個TCP鏈接,以後才能傳輸數據。TCP提供超時重發,丟棄重複數據,檢驗數據,流量控制等功能,保證數據能從一端傳到另外一端。 UDP---用戶數據報協議,是一個簡單的面向數據報的運輸層協議。UDP不提供可靠性,它只是把應用程序傳給IP層的數據報發送出去,可是並不能保證它們能到達目的地。因爲UDP在傳輸數據報前不用在客戶和服務器之間創建一個鏈接,且沒有超時重發等機制,故而傳輸速度很快安全
有人說TCP就像打電話,必須接通後才能通訊,而UDP就像發短信同樣,不須要接通就能夠發送。比喻甚是恰當啊。服務器
內容大部分來源於網絡,不喜勿噴啊!網絡
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace SocketClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(textBox2.Text)); if (comboBox1.SelectedItem.ToString() == "TCP") { TcpServer(serverIP); } else if (comboBox1.SelectedItem.ToString() == "UDP") { UdpClient(serverIP); } } #region TCP鏈接方式 /// <summary> /// TCP鏈接方式 /// </summary> /// <param name="serverIP"></param> Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public void TcpServer(IPEndPoint serverIP) { listBox1.Items.Add("客戶端啓動TCP鏈接模式"); try { tcpClient.Connect(serverIP);//鏈接 button1.Enabled = false; button1.BackColor = Color.Red; textBox1.Enabled = false; comboBox1.Enabled = false; textBox2.Enabled = false; } catch (SocketException e) { listBox1.Items.Add(string.Format("鏈接出錯:{0}", e.Message)); return; } listBox1.Items.Add("客戶端:client-->server"); new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = tcpClient.Receive(data); } catch (Exception ex) { //listBox1.Items.Add("出現異常"); break; } listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); } }).Start(); } #endregion #region UDP鏈接方式 /// <summary> /// UDP鏈接方式 /// </summary> /// <param name="serverIP"></param> Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); public void UdpClient(IPEndPoint serverIP) { listBox1.Items.Add("客戶端啓動UDP模式"); udpClient.SendTo(Encoding.UTF8.GetBytes(textBox3.Text), SocketFlags.None, serverIP); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; button1.Enabled = false; button1.BackColor = Color.Red; textBox1.Enabled = false; comboBox1.Enabled = false; textBox2.Enabled = false; new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = udpClient.ReceiveFrom(data, ref Remote);//接受來自服務器的數據 } catch (Exception ex) { // listBox1.Items.Add(string.Format("出現異常:{0}", ex.Message)); break; } listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); } }).Start(); } #endregion private void button2_Click(object sender, EventArgs e) { if (comboBox1.SelectedItem.ToString()=="TCP") { tcpClient.Send(Encoding.UTF8.GetBytes(textBox3.Text)); listBox1.Items.Add(string.Format("{0}發送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text)); } else if(comboBox1.SelectedItem.ToString()=="UDP") { listBox1.Items.Add(string.Format("{0}發送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text)); } } private void button3_Click(object sender, EventArgs e) { tcpClient.Close(); udpClient.Close(); Application.Exit(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace SocketClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(textBox2.Text)); if (comboBox1.SelectedItem.ToString() == "TCP") { TcpServer(serverIP); } else if (comboBox1.SelectedItem.ToString() == "UDP") { UdpClient(serverIP); } } #region TCP鏈接方式 /// <summary> /// TCP鏈接方式 /// </summary> /// <param name="serverIP"></param> Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public void TcpServer(IPEndPoint serverIP) { listBox1.Items.Add("客戶端啓動TCP鏈接模式"); try { tcpClient.Connect(serverIP);//鏈接 button1.Enabled = false; button1.BackColor = Color.Red; textBox1.Enabled = false; comboBox1.Enabled = false; textBox2.Enabled = false; } catch (SocketException e) { listBox1.Items.Add(string.Format("鏈接出錯:{0}", e.Message)); return; } listBox1.Items.Add("客戶端:client-->server"); new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = tcpClient.Receive(data); } catch (Exception ex) { //listBox1.Items.Add("出現異常"); break; } listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); } }).Start(); } #endregion #region UDP鏈接方式 /// <summary> /// UDP鏈接方式 /// </summary> /// <param name="serverIP"></param> Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); public void UdpClient(IPEndPoint serverIP) { listBox1.Items.Add("客戶端啓動UDP模式"); udpClient.SendTo(Encoding.UTF8.GetBytes(textBox3.Text), SocketFlags.None, serverIP); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; button1.Enabled = false; button1.BackColor = Color.Red; textBox1.Enabled = false; comboBox1.Enabled = false; textBox2.Enabled = false; new Thread(() => { while (true) { byte[] data = new byte[1024]; try { int length = udpClient.ReceiveFrom(data, ref Remote);//接受來自服務器的數據 } catch (Exception ex) { // listBox1.Items.Add(string.Format("出現異常:{0}", ex.Message)); break; } listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data))); } }).Start(); } #endregion private void button2_Click(object sender, EventArgs e) { if (comboBox1.SelectedItem.ToString()=="TCP") { tcpClient.Send(Encoding.UTF8.GetBytes(textBox3.Text)); listBox1.Items.Add(string.Format("{0}發送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text)); } else if(comboBox1.SelectedItem.ToString()=="UDP") { listBox1.Items.Add(string.Format("{0}發送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text)); } } private void button3_Click(object sender, EventArgs e) { tcpClient.Close(); udpClient.Close(); Application.Exit(); } } }
感謝園友tcp
http://www.cnblogs.com/hongfei/archive/2012/12/08/2808771.html函數
http://www.cnblogs.com/zengqinglei/archive/2013/04/27/3046119.htmlui
http://zhidao.baidu.com/link?url=HNMpttFbHTevgWwye0rPGiGuQGihHOaNNKbpJZ7CvEn8YjWr2w_5Ok_YUx1xd73yxTt9k6STVaMMuzuGINqQKKurl