在选择使用协议的时候,选择UDP必须要谨慎。在网络质量令人十分不满意的环境下,UDP协议数据包丢失会比较严重。但是由于UDP的特性:它不属于连接型协议,因而具有资源消耗小,处理速度快的优点,所以通常音频、视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。比如我们聊天用的ICQ和QQ就是使用的UDP协议。
服务端代码
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服务器
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
textBox1.Text = "127.0.0.1";
textBox2.Text = "8401";
}
/// <summary>
/// 获取本地IP
/// </summary>
private void label1_Click(object sender, EventArgs e)
{
string ip = IPAddress.Any.ToString();
textBox1.Text = ip;
}
Socket server;
private void button2_Click(object sender, EventArgs e)
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Bind(new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)));//绑定端口号和IP
//server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
listBox1.Items.Add("服务器已经成功开启!");
//开启接收消息线程
Thread t = new Thread(ReciveMsg);
t.IsBackground = true;
t.Start();
}
/// <summary>
/// 向特定ip的主机的端口发送数据
/// </summary>te
void SendMsg()
{
EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8400); //向指定的IP和端口发送消息
string msg = textBox3.Text;
server.SendTo(Encoding.UTF8.GetBytes(msg), point);
}
/// <summary>
/// 接收发送给本机ip对应端口号的数据
/// </summary>
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 button1_Click(object sender, EventArgs e)
{
if (textBox3.Text != "")
{
//开启发送消息线程
Thread t3 = new Thread(SendMsg);
t3.Start();
listBox1.Items.Add(textBox1.Text + ":" + textBox2.Text + ":" + textBox3.Text);
}
}
}
}
客户端代码
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客户端
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
textBox1.Text = "127.0.0.1";
textBox2.Text = "8400";
}
/// <summary>
/// 创建客户端
/// </summary>
Socket client;
private void button2_Click(object sender, EventArgs e)
{
///创建客户端
client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.Bind(new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)));
///线程问题
Thread thread = new Thread(ReciveMsg);
thread.IsBackground = true;
thread.Start(client);
listBox1.Items.Add("客户端已成功开启!");
}
/// <summary>
/// 向特定ip的主机的端口发送数据
/// </summary>
void SendMsg()
{
EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8401); //向指定的IP和端口发送消息
///发送内容
string msg = textBox3.Text;
///将数据发送到指定的ip的主机的端口
client.SendTo(Encoding.UTF8.GetBytes(msg), point);
}
/// <summary>
/// 接收发送给本机ip对应端口号的数据
/// </summary>
void ReciveMsg(object o)
{
while (true)
{
try
{
///用来保存发送方的ip和端口号
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
//MessageBox.Show(point.ToString());
///定义客户端接收到的信息大小
byte[] buffer = new byte[1024 * 1024];
///接收到的信息大小(所占字节数)
int length = client.ReceiveFrom(buffer, ref point);
string message = Encoding.UTF8.GetString(buffer, 0, length);
listBox1.Items.Add(point.ToString() + ":" + message);
}
catch (Exception)
{
client.Close();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox3.Text != "")
{
//开启发送消息线程
Thread t2 = new Thread(SendMsg);
t2.Start();
listBox1.Items.Add(textBox1.Text + ":" + textBox2.Text + ":" + textBox3.Text);
}
}
}
}
效果展示
代码下载地址:文章来源:https://www.toymoban.com/news/detail-525583.html
链接:https://pan.baidu.com/s/1r-V80I5fJ-8noF8YgMOlLA
提取码:qx3s文章来源地址https://www.toymoban.com/news/detail-525583.html
到了这里,关于C# 使用UDP进行网络通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!