GreySage
GreySage

Reputation: 1180

Matlab tcp/ip socket only sometimes works

I'm new to Matlab, and trying to get a simple tcp/ip socket connection to work. I have 2 simple functions:

function y = hello_socket %codegen
    %socket practice
    %open socket
    t = tcpip('0.0.0.0', 30001, 'NetworkRole', 'server');
    %wait for connection
    fopen(t)
    disp('BP-pre read')
    data = fread(t, 1);
    disp('BP-post read')
    %fclose(t);
    disp(data)
end

Which creates a server socket, waits for a connection, then reads 1 byte of data. And:

function y = hello_socket_client %codegen
    %client practice
    data = sin(1:64);
    t = tcpip('localhost', 30001, 'NetworkRole', 'client');
    fopen(t);
    fwrite(t, 5);
    fclose(t);

end

Which creates a client socket, connects and sends the number 5.

I run the server first, then the client. Now, sometimes this works and the server prints out 5. Other times it doesn't and the server gives this: "Warning: Unsuccessful read: The specified amount of data was not returned within the Timeout period." even though the code was IDENTICLE between the 2 runs.

Why does this only sometimes work? Is there a better way to do this that will work?

Edit: This code works when I execute the client function by hand in the command window, leading me to think there is some synchronization error happening. Maybe it needs a pause between opening a socket and writing to it?

Upvotes: 1

Views: 649

Answers (1)

GreySage
GreySage

Reputation: 1180

Adding a pause(1) command after opening and before writing seems to fix it. This doesn't seem like good practice to me, so any other answers are still appreciated.

Upvotes: 1

Related Questions