Network listener (TCP, UDP, etc)

5 次查看(过去 30 天)
Shane
Shane 2013-12-6
I need to create a TCP, or UDP, listener. That is, I need it to just sit around and listen and wait for a command to come in, and then when a command does come in, run various functions. Then when done, go back to listening and waiting for more commands to come in.
The problem with the simple examples I have found is that it requires proper timing, I.E. you call a fscanf (or other for example) when the data needs to be received.
Am I just using the wrong language with regards to this? Does anybody have any ideas for this or examples of how to do this?

回答(2 个)

Walter Roberson
Walter Roberson 2013-12-6
For tcp, the fopen() will not return until there has been the initial packet exchange of the TCP protocol. Each fread() will not return until timeout or full buffer or terminator condition has been reached. Thus, timing only becomes a problem if you need to be doing other things while waiting for the packets to arrive.

Pranav Athreya
Pranav Athreya 2019-8-27
I called Mathworks tech support and found the solution. I take it you are using the 'tcpclient' class with the 'read' and 'write' functions.
In order to successfully read, you must do the below:
cl = tcpclient('10.25.0.237',65434);
write(cl,unicode2native('hello'));
pause(5); % increase wait time as appropriate.
resp = read(cl, cl.BytesAvailable);
cl.BytesAvailable becomes zero immediately after a write. Once the client is ready to read, cl.BytesAvailable becomes equal to the number of incoming bytes. Then you may call read(cl, cl.BytesAvailable), and receive data.

类别

Help CenterFile Exchange 中查找有关 Interface-Based Instrument Communication 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by