fwrite tcpip连接中的以下fread是否不同? [matlab]

时间:2018-11-12 08:09:43

标签: matlab tcp

在编写类以将2个matlab实例连接在一起的过程中。实例将在单独的计算机上,但是我目前正在1台计算机上进行测试。

目前,我能够在两个Matlab之间建立连接,并且能够在它们之间发送/接收消息。

代码:

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

不知道发生了什么,因为我一直关注的examples没有这个问题。

并添加上下文。我正在尝试通过TCP-IP连接2个matlab,以便可以控制一个实例与另一个实例。我的计划是让第二个matlab等待命令代码,并在第一个matlab请求时执行指定的功能。

1 个答案:

答案 0 :(得分:1)

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'));