c#基于socket的UDP服务器和客户端实例

基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)

使用Udp协议通讯需要具备以下几个条件:

(1).建立一个套接字(Socket)

(2).绑定服务器端IP地址及端口号--服务器端

(3).通过SendTo()方法向指定主机发送消息 (需提供主机IP地址及端口)

(4).通过ReciveFrom()方法接收指定主机发送的消息 (需提供主机IP地址及端口)

c#基于socket的UDP服务器和客户端实例_第1张图片

 

下面用代码实现简单的服务器---客户端通信

服务器端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _023_socket编程_UDP协议_服务器端 {
class Program
{
private static Socket udpServer;
static void Main(string[] args) {
//1,创建socket
udpServer = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//2,绑定ip跟端口号
udpServer.Bind( new IPEndPoint ( IPAddress.Parse("192.168.1.101") ,7788 ) );

//3,接收数据
new Thread(ReceiveMessage){ IsBackground = true}.Start();
Console.WriteLine("服务器启动...");
Console.ReadKey();
}

static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom (data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
}

}
}
}

客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace _002_socket编程_udp协议_客户端 {
class Program {
static void Main(string[] args) {
//创建socket
Socket udpClient = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

while (true)
{
//发送数据
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 7788);
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
}


udpClient.Close();
Console.ReadKey();
}
}
}

执行过程:

(1)启动服务器

c#基于socket的UDP服务器和客户端实例_第2张图片

(2)启动客户端,并向服务器发送数据

//***************************2*************

C#使用UDP实现服务器与客户端通信

TCP 必须建立在连接才可以进行通信,
UDP不需要建立通信
但两者都需要监听来接收消息

服务端

c#基于socket的UDP服务器和客户端实例_第3张图片

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace UDP_windows_服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        /// 
        /// 获取本地IP
        /// 
        private void label1_Click(object sender, EventArgs e)
        {
            string ip = IPAddress.Any.ToString();
            textBox1.Text = ip;
        }
        Socket server;
        private void button1_Click(object sender, EventArgs e)
        {
            //1.创建服务器端电话
            server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //2.创建手机卡
            IPAddress iP = IPAddress.Parse(textBox1.Text);
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));
            //3.将电话卡插进电话中(绑定端口号和IP)
            server.Bind(endPoint);
            listBox1.Items.Add("服务器已经成功开启!");
            //开启接收消息线程
            Thread t = new Thread(ReciveMsg);
            t.IsBackground = true;
            t.Start();
        }
        /// 
        /// 向特定ip的主机的端口发送数据
        /// te
        void SendMsg()
        {
            //string hostName = Dns.GetHostName();   //获取本机名
            //IPHostEntry localhost = Dns.GetHostEntry(hostName);   //获取IPv6地址
            //IPAddress localaddr = localhost.AddressList[0];
            EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(textBox2.Text));
            string msg = textBox3.Text;
            server.SendTo(Encoding.UTF8.GetBytes(msg), point);
        }
        /// 
        /// 接收发送给本机ip对应端口号的数据
        /// 
        void ReciveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024 * 1024];
                int length = server.ReceiveFrom(buffer, ref point);//接收数据报
                string message = Encoding.UTF8.GetString(buffer, 0, length);
                listBox1.Items.Add(point.ToString() + ":" + message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                //开启发送消息线程
                Thread t2 = new Thread(SendMsg);
                t2.Start();
            }
        }
    }
}

客户端

c#基于socket的UDP服务器和客户端实例_第4张图片

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace UDP_windows_客户端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// 
        /// 创建客户端
        /// 
        Socket client;

        private void button1_Click(object sender, EventArgs e)
        {
            ///创建客户端
            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress iP = IPAddress.Parse(textBox1.Text);
            ///端口号
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));
            ///建立与服务器的远程连接
            client.Connect(endPoint);
            ///线程问题
            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
            listBox1.Items.Add("客户端已成功开启!");
        }
        /// 
        /// 向特定ip的主机的端口发送数据
        /// 
        void SendMsg()
        {
            ///获取IP与端口号
            EndPoint point = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
            ///发送内容
            string msg = textBox3.Text;
            ///将数据发送到指定的ip的主机的端口
            client.SendTo(Encoding.UTF8.GetBytes(msg), point);
        }
        /// 
        /// 接收发送给本机ip对应端口号的数据
        /// 
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    ///用来保存发送方的ip和端口号
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);
                    ///定义客户端接收到的信息大小
                    byte[] buffer = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = client.Receive(buffer);
                    string message = Encoding.UTF8.GetString(buffer, 0, length);
                    listBox1.Items.Add(point.ToString() + ":" + message);
                }
                catch (Exception)
                {
                    client.Close();
                }
                
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                //开启发送消息线程
                Thread t2 = new Thread(SendMsg);
                t2.Start();
            }
            listBox1.Items.Add(textBox3.Text);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}

c#基于socket的UDP服务器和客户端实例_第5张图片

 

你可能感兴趣的