fwrite другой следующий fread в соединении tcpip? [MATLAB] - PullRequest
0 голосов
/ 12 ноября 2018

В процессе написания класса для соединения 2 экземпляров matlab вместе. экземпляры будут на отдельных компьютерах, но в настоящее время я тестирую на 1 компьютере.

В настоящее время я могу установить соединение между обоими matlabs, и я могу отправлять / получать сообщения между ними.

код:

classdef connectcompstogether<handle
    properties
        serverIP
        clientIP
        tcpipServer
        tcpipClient
        Port = 4000;
        bsize = 8;
        Message
    end

    methods
        function gh = connectcompstogether(~)
            % gh.serverIP = '127.0.0.1';
            gh.serverIP = 'localhost';
            gh.clientIP = '0.0.0.0';
        end

        function SetupServer(gh)
            gh.tcpipServer = tcpip(gh.clientIP,gh.Port,'NetworkRole','Server');
            set(gh.tcpipServer,'OutputBufferSize',gh.bsize);
            fopen(gh.tcpipServer);
            display('Established Connection')
        end

        function SetupClient(gh)
            gh.tcpipClient = tcpip(gh.serverIP,gh.Port,'NetworkRole','Client');
            set(gh.tcpipClient,'InputBufferSize',gh.bsize);
            set(gh.tcpipClient,'Timeout',30);
            fopen(gh.tcpipClient);
            display('Established Connection')
        end
        function CloseClient(gh)
            fclose(gh.tcpipClient);
        end
    end
    methods
        function sendmessage(gh,message)
            fwrite(gh.tcpipServer,message,'double');
        end

        function recmessage(gh)
            gh.Message = fread(gh.tcpipClient,gh.bsize);
        end
    end
end

matlab 1

gh = connectcompstogether;
gh.SetupServer();
gh.sendmessage(555);

Matlab 2

gh = connectcompstogether;
gh.SetupClient();
gh.recmessage();

отправленное сообщение является 8-битным двойным 555 . Однако при просмотре полученного сообщения получается матрица

64
129
88

не понимаю, что происходит в качестве примеров Я следовал, у меня нет этой проблемы.

и добавить контекст. Я пытаюсь соединить 2 MATLAB через TCP-IP, чтобы я мог контролировать один экземпляр с другим. Мой план состоит в том, чтобы второй matlab ожидал кодов команд и выполнял указанные функции, когда 1-й запрос matlab.

1 Ответ

0 голосов
/ 12 ноября 2018

tcpip / fread точность по умолчанию равна uchar , поэтому по умолчанию fread выведет массив столбцов из 8-разрядных целых чисел без знака.

Вам либо нужно указать, что ожидается двойное число:

%size divided by 8, as one 8-byte value is expected rather than 8 1-byte values
gh.Message = fread(gh.tcpipClient,gh.bsize/8,'double');

Или typecast массив uint8 в двойном виде:

rawMessage = fread(gh.tcpipClient,gh.bsize); %implicit: rawMessage is read in 'uchar' format 
% cast rawMessage as uint8 (so that each value is stored on a single byte in memory, cancel MATLAB automatic cast to double)
% then typecast to double (tell MATLAB to re-interpret the bytes in memory as double-precision floats)
% a byteswap is necessary as bytes are sent in big-endian order while native endianness for most machines is little-endian
gh.Message = swapbytes(typecast(uint8(rawMessage),'double'));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...