当前位置:   article > 正文

C# UDP实现数据收发_c#udp接收和发送

c#udp接收和发送

因为UDP是无连接的,无需建立连接,就可以收发数据。使用Sokit 工具测试编写的代码是否正常工作。

开启UDP侦听IP和端口,编写代码实现数据收发,服务端如下:

编写简易代码UI如下:

向IP 127.0.0.1,9902 端口发送数据,测试发送数据OK

测试接收服务端发送的数据OK

1. UI设计
<Window x:Class="Udp_Test1.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:Udp\_Test1"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="UDP Test1" Height="450" Width="500">

    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="3"/>
            <Setter Property="Padding" Value="2"/>
        </Style>

        <Style TargetType="TextBox">
            <Setter Property="Margin" Value="3"/>
           <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>

    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" Margin="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Column="0" >服务器IP地址:</TextBlock>
            <TextBox Grid.Column="1" x:Name="txtServerIP" >127.0.0.1</TextBox>
            <TextBlock Grid.Column="2" >服务器端口:</TextBlock>
            <TextBox Grid.Column="3" x:Name="txtServerPort" >9902</TextBox>
        </Grid>

        <DockPanel Grid.Row="1" Margin="3">
            <TextBlock DockPanel.Dock="Left">发送数据:</TextBlock>

            <Button DockPanel.Dock="Right" x:Name="btnSendData" Click="btnSendData_Click" Margin="3" VerticalAlignment="Center">发送数据</Button>
            <TextBox x:Name="txtSendData"></TextBox>
        </DockPanel>

        <TextBlock Grid.Row="2">
            接收到服务器发来的数据:
        </TextBlock>

        <TextBox x:Name="txtRecivedMessage" Grid.Row="3" TextWrapping="Wrap" Margin="5" VerticalAlignment="Stretch" VerticalScrollBarVisibility="Visible"></TextBox>
    </Grid>

</Window>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
2. 代码设计
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Udp_Test1
{

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        static Socket client;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            client.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9901));
            //接收发送给本机ip对应端口号的数据报

            Task.Run(async() =>
            {
                while(true)
                {
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                    byte[] buffer = new byte[1024];
                    int length = client.ReceiveFrom(buffer, ref point);//接收数据报
                    string message = Encoding.UTF8.GetString(buffer, 0, length);

                    await this.txtRecivedMessage.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                    {
                        txtRecivedMessage.AppendText("Sever (" + point.ToString() + ") :" +message + "\r\\n");
                    }));

                }

            });

        }

        private void btnSendData_Click(object sender, RoutedEventArgs e)
        {
            //向特定IP的主机的端口发送数据--ServerIP,Port
            //EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9902);

            EndPoint point = new IPEndPoint(IPAddress.Parse(txtServerIP.Text), int.Parse(txtServerPort.Text));
            client.SendTo(Encoding.UTF8.GetBytes(txtSendData.Text), point);

        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

简单的实现了UDP数据的收发。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/895538
推荐阅读
相关标签
  

闽ICP备14008679号