udp
udp和tcp都是传输协议,最大的不同是,tcp通信前需要建立连接,是更可靠的通信协议,而udp是一个无连接的传输协议,可直接发送数据。两种协议不分优劣,各有各的应用场景,实际应用往往会同时使用两种协议。
C#实现
C#代码实现udp通信的步骤比较简单。
假设:A要向B发送消息。
做法:首先,B需要创建UdpClient,监听某端口;然后,A创建UdpClient,向B的监听端口发送消息;最后B接收到消息,处理消息;
示例程序运行如下:
文章来源:https://www.toymoban.com/news/detail-568618.html
主要源码
接收类
public class UdpReceiver
{
public UdpReceiver(int _port)
{
port = _port;
}
int port;
public void StartReceiveData(Action<string> receiveData)
{
Task.Run(() => { receiveDataAsync(receiveData); });
}
private async void receiveDataAsync(Action<string> receiveData)
{
UdpClient udpClient = new UdpClient(port);
while (true)
{
var result = await udpClient.ReceiveAsync();
string message = Encoding.UTF8.GetString(result.Buffer);
receiveData?.Invoke(message);
}
}
}
发送类
public class UdpSender
{
public UdpSender(string remoteIp, int port)
{
remoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteIp), port);
}
IPEndPoint remoteEndPoint = null;
public void Send(string message)
{
UdpClient udpClient = new UdpClient();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.Send(data, data.Length, remoteEndPoint);
udpClient.Close();
}
}
监听命令
public DelegateCommand StartListen
{
get
{
return new DelegateCommand((port) =>
{
int p = 0;
if (!Int32.TryParse(port.ToString(), out p) || p<=1024)
{
MessageInfos.Add(new MessageInfo() { From = "系统消息", Message = "本机端口输入有误!" });
return;
}
try
{
StartEnabled = false;
UdpReceiver receiver = new UdpReceiver(p);
receiver.StartReceiveData((msg) =>
{
MessageInfos.Add(new MessageInfo() { From = msg.Split(',')[0], Message = msg.Split(',')[1] });
});
MessageInfos.Add(new MessageInfo() { From = "系统消息", Message = "正在监听端口:"+p.ToString() });
}
catch (Exception e)
{
MessageInfos.Add(new MessageInfo() { From = "系统消息", Message = "错误:" + e.Message });
startEnabled = true;
}
});
}
}
发送命令
public DelegateCommand Send
{
get
{
return new DelegateCommand((msg) =>
{
if (string.IsNullOrEmpty(RemoteIp) || RemotePort <= 0)
{
MessageInfos.Add(new MessageInfo() { From = "系统消息", Message = "对方IP及端口输入有误!"});
return;
}
UdpSender sender = new UdpSender(RemoteIp, RemotePort);
try
{
sender.Send(LocalIp + ":" + LocalPort.ToString()+","+msg.ToString());
MessageInfos.Add(new MessageInfo() { From = LocalIp + ":" + LocalPort.ToString(), Message = msg.ToString() });
}
catch (Exception e)
{
MessageInfos.Add(new MessageInfo() { From = "系统消息", Message = "错误:" + e.Message });
}
});
}
}
UI绑定
<Window x:Class="UdpDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:UdpDemo"
mc:Ignorable="d"
Title="Udp点对点通信示例" Height="360" Width="600">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Margin="20,5">
<TextBlock Text="本机IP"/>
<TextBox Text="{Binding LocalIp}" Width="120" Margin="5,0" IsReadOnly="True" />
<TextBlock Text="本机端口" Margin="5,0"/>
<TextBox x:Name="txt_Port" Text="{Binding LocalPort}" Width="60" Margin="5,0" IsReadOnly="{Binding Listening}" />
<Button Width="80" Content="开始监听" Command="{Binding StartListen}" CommandParameter="{Binding ElementName=txt_Port,Path=Text}" IsEnabled="{Binding StartEnabled}" Margin="5,0" />
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Bottom" Margin="20,5">
<TextBlock Text="对方IP"/>
<TextBox Text="{Binding RemoteIp}" Width="120" Margin="5,0" />
<TextBlock Text="对方端口" Margin="5,0"/>
<TextBox Text="{Binding RemotePort}" Width="60" Margin="5,0" />
<Button Width="80" Content="发送消息" Command="{Binding Send}" CommandParameter="{Binding ElementName=txt_msg,Path=Text}" Margin="5,0" />
<TextBox x:Name="txt_msg" Width="160" Text="这是一个测试消息!"/>
</StackPanel>
<ListView Grid.Row="2" ItemsSource="{Binding MessageInfos}" Margin="5">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,2">
<TextBlock Text="{Binding From}" Foreground="Gray"/>
<TextBlock Text="{Binding Message}" Foreground="Black"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
完整源码分享
完整源码下载:下载源码
(备注:使用vs2022打开)文章来源地址https://www.toymoban.com/news/detail-568618.html
到了这里,关于C#实现udp点对点通信的完整示例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!