Read time data from server fast without new connection by tcpclient
1 次查看(过去 30 天)
显示 更早的评论
Hello everyone,
I would like to get the current time from a website, similar to the answer in
https://de.mathworks.com/matlabcentral/answers/477336-how-can-i-get-date-and-time-from-nist-server, where the following was described:
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!
0 个评论
采纳的回答
Zinea
2024-4-10
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();
pause(5);
time2 = fetchNewTime();
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!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!