我正在尝试在C#中编写一个简单的UDP程序,它在localhost上发送和接收数据。我是C#的初学者,但在MATLAB上要好得多,所以不是用C#编写服务器和客户端,而是决定使用C#发送数据并在MATLAB中接收它。
我尝试了两种方法来发送数据。使用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案例中得到它?有没有办法避免这个错误?
答案 0 :(得分:1)
我知道您在同一台计算机上使用相同的端口用于MATLAB和C#。因此,操作系统不允许从不同的应用程序打开相同的端口。
UDP允许从不同的端口发送和接收数据报,因此如果两个应用程序在同一台计算机上运行,则为不同的应用程序使用不同的端口。
UdpClient sendingClient = new UdpClient(62746); // Some different port to listen
sendingClient.Send(sendBytes, sendBytes.Length, ipEndPoint);