Read time data from server fast without new connection by tcpclient
조회 수: 6 (최근 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개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!