[英]Why can't I receive text sent to localhost using UdpClient in C#?
我试图用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情况下却没有得到错误? 有办法避免该错误吗?
我了解您在同一台计算机上为MATLAB和C#使用了相同的端口。 因此,操作系统不允许从不同的应用程序打开相同的端口。
UDP允许从不同的端口发送和接收数据报,因此,如果两个应用程序都在同一台计算机上运行,则对不同的应用程序使用不同的端口。
UdpClient sendingClient = new UdpClient(62746); // Some different port to listen
sendingClient.Send(sendBytes, sendBytes.Length, ipEndPoint);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.