Skip to content

Instantly share code, notes, and snippets.

@julianthome
Created December 7, 2016 10:25
Show Gist options
  • Save julianthome/0731d69081cedf357a8b384c191af8ad to your computer and use it in GitHub Desktop.
Save julianthome/0731d69081cedf357a8b384c191af8ad to your computer and use it in GitHub Desktop.
IPC between Matlab and Java programs. Server process which can be started in Matlab by invoking extserver(<port>) and Java Client wich can be invoked from Java program for sending data to Matlab
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Arrays;
import java.util.Set;
public class Client {
public static void main(String[] args) {
String sentence = " Y = [3,2,3,5]\n";
byte [] b = Arrays.copyOf(sentence.getBytes(), 512);
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 30001);
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream outToServer = null;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
outToServer.write(b, 0, 512);
outToServer.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outToServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
% based on http://nl.mathworks.com/matlabcentral/fileexchange/25249-tcpip-socket-communications-in-matlab-using-java-classes/content/server.m
function extserver(output_port)
import java.net.ServerSocket
import java.io.*
server_socket = [];
output_socket = [];
try
fprintf(1, ['Waiting for client to connect to port : %d\n'], output_port);
% wait for 1 second for client to connect server socket
server_socket = ServerSocket(output_port);
server_socket.setSoTimeout(70000);
in_socket = server_socket.accept;
fprintf(1, 'Client connected\n');
% get a buffered data input stream from the socket
in_stream = in_socket.getInputStream;
d_in_stream = DataInputStream(in_stream);
pause(0.5);
bytes_available = in_stream.available
fprintf(1, 'Reading %d bytes\n', bytes_available)
message = zeros(1, bytes_available, 'uint8');
for i = 1:bytes_available
message(i) = d_in_stream.readByte;
end
message = char(message)
% clean up
server_socket.close;
in_socket.close;
catch
if ~isempty(server_socket)
server_socket.close
end
if ~isempty(output_socket)
output_socket.close
end
% pause before retrying
pause(1);
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment