tcpserver not getting any data if client writes 4096 bytes or more

12 views (last 30 days)
I am playing around with tcpserver and tcpclient. I came across an issue when writing >=4096 bytes to the server. This is my server:
server = tcpserver('0.0.0.0', 10000);
And this is my client:
client = tcpclient('X.X.X.X', 10000);
n = 4096;
write(client, uint8(ones(1, n)))
If n<4096 life is easy and everything goes fine. However, if n>=4096, I get server.NumBytesAvailable = 0. Also, if I retry the last line in my client, I get the following error:
Error using asyncio.MessageHandler/onError (line 31)
An existing connection was forcibly closed by the remote host
I suspect it has something to do with buffers. I know there is a buffer size in udp(), but I cannot find any similar property in tcpserver.
Thanks in advance.

Answers (1)

Zinea
Zinea on 19 Feb 2024
I can see that you are unable to send more than 4096 bytes from client to server using “write” function in MATLAB R2021a using tcp. I have given below a working code for your use. Client is successfully able to send >= 4096 bytes to Server.
Below is the code for client:
% Create a TCP client to connect to the server
client = tcpclient(serverAddress, serverPort);
% Define the amount of data to send
n = 4096;
dataToSend = uint8(ones(1, n));
% Write the data to the server
write(client, dataToSend);
Below is the code for server :
% Wait for a connection
while true
if server.NumBytesAvailable >= 4096
data = read(server, server.NumBytesAvailable, 'uint8');
% Process your data here
disp(data);
break;
end
end
Note – Once a data is read, it is removed from the buffer. So after one read, “NumBytesAvailable” will give 0.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!