Read time data from server fast without new connection by tcpclient

6 visualizzazioni (ultimi 30 giorni)
Hello everyone,
I would like to get the current time from a website, similar to the answer in
Nist_Time = tcpclient('time.nist.gov',13);
tcpdata = read(Nist_Time);
The read command works fine for the first time, but if I try
tcpdata = read(Nist_Time);
again, only
[]
is returned. I suspect that the connection to the server is gone after the first call, but I don't know how to maintain it.
I look forward to your feedback!

Risposta accettata

Zinea
Zinea il 10 Apr 2024
Hi PeLa,
The connection to the server remains after the first read. This can be checked using 'Nist_Time.Status' which returns the value ‘open’.
The issue of the second read returning an empty array is probably due to the reason that the server protocol is designed in such a way that it does not send additional data after the first message. The server keeping the TCP connection open might be an implementation detail or a timeout feature.
Since the server sends data once per connection, the most straightforward approach is to establish a new connection with the server every time data is to be read.
Here is a code snippet where the function ‘fetchNewTime()’ is called for each read:
time1 = fetchNewTime();
Time now: 11:03:10
pause(5);
time2 = fetchNewTime();
Time now: 11:03:16
function timeStr = fetchNewTime()
Nist_Time = tcpclient('time.nist.gov', 13);
pause(0.5);
tcpdata = read(Nist_Time);
if numel(tcpdata) >= 24
timeStr = char(tcpdata);
timeStr = timeStr(17:24);
disp(['Time now: ', timeStr])
else
disp('Not enough data received in the read attempt.')
end
end
NOTE: Add a pause after the call to ‘tcpclient’ as there may be delay in fetching the data from the server.
Hope it helps!

Più risposte (0)

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by