Hello,

I've implemented a simple TCP server using the ServerSocket class (code below) to communicate with a client. They should just exchange strings. The client comes off-the-shelf with a sensor I need to use and, although I don't have access to its source code, I know all the commands I can R/W from it. The server starts listening and as soon as the client connects to it, the client is supposed to send a string with 3 initialization commands of the type "command 1\r\n command 2\r\n command 3\r\n". \r\n denotes the end of a command.

The problem is, my server can't seem to read this initial string and then the client has a timeout because the server doesn't reply appropriately. I know the initial string packet is being sent because I can see it with a network sniffer (Wireshark). Does anyone have an idea why my server hasn't been able to read it?

Thanks,
Glauber

function main
 
    import java.net.ServerSocket
    import java.io.*
 
    port = 16544;
    server = [];
    s = [];
    command = [];
 
    try
        % Creates the server socket if port is available
        fprintf(1, ['Waiting for the client to connect...\n']);
        server = ServerSocket(port);
 
        % Listens on the specified port
        server.setSoTimeout(0); % Wait forever
        s = server.accept; % Start listening
        fprintf(1, 'Server connected\n');
 
        % Socket options
        s.setKeepAlive(true) % Heartbeat
        s.setTcpNoDelay(true) % Nable's algorithm off
 
        % R/W streams
        in = BufferedReader(InputStreamReader(s.getInputStream));
        out = DataOutputStream(s.getOutputStream);
 
        while true
 
            % read data
            command = in.readLine;
            if ~isempty(command)
                command
            end
 
            command = char(command);
 
            % write data
            CRLF = [char(13),char(10)];
            switch command
                case 'command 1'
                    out.writeBytes(['reply 1',CRLF]);
                    out.flush;
                case 'command 2'
                    out.writeBytes(['reply 2',CRLF]);
                    out.flush;
            end
        end
 
        % clean up
        server.close
        s.close
        return
 
    catch exception
 
        if ~isempty(server)
            server.close
        end
 
        if ~isempty(s)
            s.close
        end
 
        throw(exception)
    end
end