udp - Why can't I receive text sent to localhost using UdpClient in C#? -
i trying write simple udp program in c# sends , receives data on localhost. beginner in c# better @ matlab instead of writing server , client in c#, decided send data using c# , receive in matlab.
i tried 2 approaches send data. using socket class worked, using udpclient class failed.
before running code, run matlab code set callback function print received datagram.
only 1 region active in each run. comment out other one.
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 @ 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 } } }
i getting
only 1 usage of each socket address (protocol/network address/port) permitted
error when run code in region 2.
however, when run code in region 1 works expect , receive data in matlab without problems.
here matlab code. have used code in other applications, highly doubt there wrong it.
fclose(instrfindall); %close 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);
and callback function:
function cbdatareceived(hobj, eventdata, udpobj) bytesavailable = get(udpobj, 'bytesavailable'); receiveddatagram = fread(udpobj, bytesavailable); disp(char(receiveddatagram)); end
so, why getting error in udpclient case , not getting in socket case? there way avoid error?
i understand using same port both matlab , c# on same computer. thus, operating system not allow open same port different applications.
udp allows sending , receiving datagrams different ports, use different ports different applications if both applications running on same computer.
udpclient sendingclient = new udpclient(62746); // different port listen sendingclient.send(sendbytes, sendbytes.length, ipendpoint);
Comments
Post a Comment