简单使用SOCKET,TCP,UDP模式之间的通信

TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议,由IETF的RFC 793定义。在简化的计算机网络OSI模型中,它完成第四层传输层所指定的功能,用户数据报协议(UDP)是同一层内[1] 另一个重要的传输协议。在因特网协议族(Internet protocol suite)中,TCP层是位于IP层之上,应用层之下的中间层。不同主机的应用层之间经常需要可靠的、像管道一样的连接,但是IP层不提供这样的流机制,而是提供不可靠的包交换。[1] 
应用层向TCP层发送用于网间传输的、用8位字节表示的数据流,然后TCP把数据流分区成适当长度的报文段(通常受该计算机连接的网络的数据链路层的最大传输单元([1] MTU)的限制)。之后TCP把结果包传给IP层,由它来通过网络将包传送给接收端实体[1] 的TCP层。TCP为了保证不发生丢包,就给每个包一个序号,同时序号也保证了传送到接收端实体的包的按序接收。然后接收端实体对已成功收到的包发回一个相应的确认(ACK);如果发送端实体在合理的往返时延(RTT)内未收到确认,那么对应的数据包就被假设为已丢失将会被进行重传。TCP用一个校验和函数来检验数据是否有错误;在发送和接收时都要计算校验和。[1] 
 
UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interconnection,开放式系统互联) 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务,IETF RFC 768是UDP的正式规范。UDP在IP报文的协议号是17。
UDP协议全称是用户数据报协议[1] ,在网络中它与TCP协议一样用于处理数据包,是一种无连接的协议。在OSI模型中,在第四层——传输层,处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。UDP用来支持那些需要在计算机之间传输数据的网络应用。包括网络视频会议系统在内的众多的客户/服务器模式的网络应用都需要使用UDP协议。UDP协议从问世至今已经被使用了很多年,虽然其最初的光彩已经被一些类似协议所掩盖,但是即使是在今天UDP仍然不失为一项非常实用和可行的网络传输层协议。
与所熟知的TCP(传输控制协议)协议一样,UDP协议直接位于IP(网际协议)协议的顶层。根据OSI(开放系统互连)参考模型,UDP和TCP都属于传输层协议。UDP协议的主要作用是将网络数据流量压缩成数据包的形式。一个典型的数据包就是一个二进制数据的传输单位。每一个数据包的前8个字节用来包含报头信息,剩余字节则用来包含具体的传输数据。
 

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

原文地址:https://www.cnblogs.com/jason-davis/p/4636144.html