Matlab自带的socket通信存在一些问题,所以引入了JAVA
数组传递的方法是先将数组转换为一维数组,再转为字符串,最后加入换行符
- sever demo
function serverdemo(output_port)
import java.net.ServerSocket
import java.io.*
output_socket = [];
server_socket = ServerSocket(output_port);
while true
try
disp("监听等待")
output_socket = server_socket.accept;
disp("连接成功")
input_stream = output_socket.getInputStream;
input_reader = BufferedReader(InputStreamReader(input_stream));
disp("数据读取")
while true
%阻塞方法,会一直等待数据,直到遇到换行符
data = input_reader.readLine();
data = str2num(data)
end
input_reader.close;
output_socket.close;
break;
catch
pause(1)
end
end
end
- client demo
function clientdemo(host,port)
import java.net.Socket
import java.io.*
socket = [];
%若发送多维数组将数据拉为一维的 data(:)
data=ones(1,10);
while true
try
disp("尝试连接")
socket = Socket(host,port);
disp("连接成功")
output_stream = DataOutputStream(socket.getOutputStream);
disp("数据发送")
while true
%将数组转换为char类型 char(num2str(data)),并且加一个换行符 char(13,10)',不然会接收端会阻塞
output_stream.writeBytes([char(num2str(data)),char(13,10)']);
output_stream.flush;
pause(2);
end
output_stream.close;
input_socket.close;
break;
catch
pause(1)
end
end
end
- run
serverdemo('8888')
clientdemo('127.0.0.1','8888')