这是学习Socket制作的,是两个项目,分别为客户端和服务器端,在测试的时候需要同时运行起来。
UDP一般和TCP协议进行比较,具体不同可百度大神的文章学习。根据我的理解,UDP协议中最重要的两个方法是ReceiveFrom()和SendTo(), “UDP应用上已经无严格意义上的真正的服务器和客户端之分了”,其实就是通过IP地址和端口进行数据的发送和接收。
在学习的过程中碰到了几个难点:
1、无论是服务端和客户端在接收信息的时候,设置缓存区接收信息如下
byte[] data = new byte[1024];
recv= SocClient.ReceiveFrom(data, ref RemotePoint);
this.Dispatcher.Invoke(new Action(() => { tblock_message.Text += (RemotePoint.ToString()+Encoding.Default.GetString(data,0,recv)); }));
如果设置的读取信息语句如下,
Encoding.Default.GetString(data)
则文本框上就会将data中1204个字节都显示出来,很影响效果,所以改成
Encoding.Default.GetString(data,0,recv)
则显示的正常。
2、由于接收信息的是个单独的线程,如果给主界面上的文本框中添加文字,则会提示“调用线程无法访问此对象,因为另一个线程拥有该对象”,所以设置如下语句进行解决:
this.Dispatcher.Invoke(new Action(() => { tblock_message.Text += (RemotePoint.ToString()+Encoding.Default.GetString(data,0,recv)); }));
下面贴出代码:
服务端 前端:
<Window x:Class="UdpServe.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:UdpServe"
mc:Ignorable="d"
Title="服务器端" Height="375" Width="524">
<Grid>
<Button Name="btn_send" Content="发送信息" HorizontalAlignment="Left" Margin="333,244,0,0" VerticalAlignment="Top" Width="75" Click="btn_send_Click" />
<TextBox Name="tblock_message" ScrollViewer.VerticalScrollBarVisibility="Auto" Background="Cornsilk" HorizontalAlignment="Left" Margin="34,10,0,0" VerticalAlignment="Top" Height="208" Width="464"/>
<Button Name="btn_connect" Content="开启服务" HorizontalAlignment="Left" Margin="243,244,0,0" VerticalAlignment="Top" Width="75" Click="btn_connect_Click"/>
<Label Content="IP地址" HorizontalAlignment="Left" Margin="33,269,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="