Matlab - PC TCP / IP communication

Matlab - PC TCP / IP communication

Function Description
tcplicent Create a TCP / IP client object, for TCP / IP communication
read Reading the data on the remote host via TCP / IP
write Transmitting data to a remote host via TCP / IP

Create a TCP / IP connection

Creating an object using the host name

t = tcpclient("www.maths.com",80);
/*当使用主机名(例如指定的 Web 地址或 'localhost')连接时,将根据网络接口的配置解析 IP 地址。其结果可能会将地址解析为 IPv4 地址或 IPv6 地址。如果 TCP/IP 服务器只接受传入连接为某种类型的地址,例如 IPv4 地址,则在创建客户端时可能需要使用显式 IP 地址,而不是主机名。*/

Create objects using the IP address

t = tcpclient('172.28.154.231', 4012);
/*使用IP,port建立TCP/IP对象*/

Timeout

t = tcpclient('172.28.154.231', 4012, 'Timeout', 20);
/*指定读写操作的等待时间(以秒为单位)*/
/*Timeout 不设置时,默认为10*/
/*如果指定的地址或端口无效,或者无法建立与服务器的连接,则不会创建对象。*/

ConnectTimeout

t = tcpclient('172.28.154.231', 4012, 'ConnectTimeout', 10)
/*指定对远程主机的连接请求是成功还是失败的最长时间(以秒为单位)*/
/*此参数数值仅可以在创建期间修改,*/
/*如果指定的地址或端口无效,或者无法建立与服务器的连接,则不会创建对象。*/

Changes to the Client after creation

<object_name>.<property_name> = <property_value>;
t.Timeout = 30;

Read and write data

read

read(t)                 //读取所有发送的发送的数据。

read(t, 5)              //仅读取五个字节的数。

read(t, 10, 'double')   //读取十个字节的数据,并且转化为double类型。

write

/*write 函数以同步方式将数据写入与 tcpclient 对象连接的远程主机。首先指定数据,然后写入该数据。此函数一直等到指定数量的值写入远程主机。*/
/*在此示例中,tcpclient 对象 t 已存在。*/

data = 1:10;     //创建数组data
write(t, data);  //输出数据

/*对于任何读写操作,该数据类型将转换为 uint8 以便传输数据。如果指定了其他数据类型,则可以将其重新转换为所设置的任何数据类型。*/

read and write

>>t = tcplicent('172.28.154.231',1045)       //创建TCP/IP Client

>>data = uint8(1:10)                       //创建data数组

>>whos data                               //检查data数据
Name     Size     Bytes     Class     Attributes

data     1x10        10     uint8

>>write(t, data)                            //发送data数据

>>t.BytesAvailable                          //检查是否使用BytesAvailable属性写入了数据

ans = 

    10
    
>>read(t)                                   //从服务器读取数据

ans = 

  1    2    3    4    5    6    7    8    9    10
  
>>clear t                                   //清楚tcp/ip对象 t      
  


Get data from the server

t = tcpclient('172.28.154.231', 1045)       //创建TCP/IP Client


data = read(t, 30, 'double');
/*使用 read 函数获取数据。对于来自 3 个传感器(温度、压力和湿度)的 10 个样本,指定要读取的字节数为 30。将数据类型指定为 double。*/

data = reshape(data, [3, 10]);
/*将 1×30 数据重构为 10×3 数据,各用一列来显示温度、压力和湿度。*/

subplot(311);                           //绘制温度图。
plot(data(:, 1));

subplot(312);                           //绘制压力图。
plot(data(:, 2));

subplot(313);                           //绘制湿度图。
plot(data(:, 3));

clear t                                 //清除对象断开连接

Close TCP / IP connection

clear <Objectname>;

Guess you like

Origin www.cnblogs.com/zhouhaocheng---yijianqinxin/p/12346566.html