[英]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.