0

我正在尝试用 C# 编写一个简单的 UDP 程序,该程序在 localhost 上发送和接收数据。我是 C# 的初学者,但在 MATLAB 方面要好得多,所以我决定使用 C# 发送数据并在 MATLAB 中接收数据,而不是用 C# 编写服务器和客户端。

我尝试了两种发送数据的方法。使用 Socket 类有效,但使用 UdpClient 类失败。

在运行这段代码之前,我运行了 MATLAB 代码来设置回调函数来打印接收到的数据报。

每次运行中只有一个区域处于活动状态。我注释掉另一个。

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

namespace udp1
{
    class Program
    {
        const int port = 62745; //Chosen at random
        static void Main(string[] args)
        {
            string str = "Hello World!";
            byte[] sendBytes = Encoding.ASCII.GetBytes(str);

            #region 1 Send data using socket class
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
            sock.SendTo(sendBuff, ipEndPoint);
            Console.ReadLine();
            #endregion

            #region 2 Send data using UdpClient class
            UdpClient sendingClient = new UdpClient(port);
            sendingClient.Send(sendBytes, sendBytes.Length);
            #endregion
        }
    }
}

我正进入(状态

每个套接字地址(协议/网络地址/端口)通常只允许使用一次

在区域 2 中运行代码时出错。

但是,当我在区域 1 中运行代码时,一切正常,并且我在 MATLAB 中接收数据没有任何问题。


这是我的 MATLAB 代码。我在其他应用程序中使用过这段代码,所以我非常怀疑它有什么问题。

fclose(instrfindall); %Close all udp objects
%UDP Configuration
udpConfig.ipAddress = '127.0.0.1';
udpConfig.portAddress = 62745;

udpObj = udp(udpConfig.ipAddress, udpConfig.portAddress, ...
    'LocalPort',        udpConfig.portAddress, ...
    'ByteOrder',        'bigEndian');

set(udpObj, 'datagramTerminateMode', 'on');
set(udpObj, 'datagramReceivedFcn', {@cbDataReceived, udpObj});

fopen(udpObj);

以及回调函数:

function cbDataReceived(hObj, eventdata, udpObj)
    bytesAvailable = get(udpObj, 'BytesAvailable');
    receivedDatagram = fread(udpObj, bytesAvailable);
    disp(char(receivedDatagram));
end

那么,为什么我在 UdpClient 案例中得到错误,而在 Socket 案例中没有得到它?有没有办法避免这个错误?

4

1 回答 1

1

我了解到您在同一台计算机上为 MATLAB 和 C# 使用相同的端口。因此,操作系统不允许从不同的应用程序打开相同的端口。

UDP 允许从不同的端口发送和接收数据报,因此如果两个应用程序在同一台计算机上运行,​​则为不同的应用程序使用不同的端口。

UdpClient sendingClient = new UdpClient(62746); // Some different port to listen
sendingClient.Send(sendBytes, sendBytes.Length, ipEndPoint);
于 2013-04-18T11:58:44.410 回答