标签:
TCP与UDP区别
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(); } } }
感谢园友
http://www.cnblogs.com/hongfei/archive/2012/12/08/2808771.html
http://www.cnblogs.com/zengqinglei/archive/2013/04/27/3046119.html
http://zhidao.baidu.com/link?url=HNMpttFbHTevgWwye0rPGiGuQGihHOaNNKbpJZ7CvEn8YjWr2w_5Ok_YUx1xd73yxTt9k6STVaMMuzuGINqQKK
标签:
原文地址:http://www.cnblogs.com/jason-davis/p/4636144.html