views:

369

answers:

2

Hi,

I'm trying to use the Java commands pw.println() and br.readLine() in Matlab because I have set up a socket (input_socket2) between Matlab and a command-line program I want to control using Java classes BufferedReader and PrintWriter. Before the following snippet of code, I implemented another socket that goes between 2 computers. This works great and I also know that the following snippet of code successfully opens up a communication line between Matlab and the other program. However, Matlab throws an error at pw.println('noop'). I think it has something to do with syntax, but I'm not sure how to write the command in Matlab syntax then:

try
    input_socket2 = Socket(host2,port2);
    input_stream2   = input_socket2.getInputStream;
    d_input_stream2 = DataInputStream(input_stream2);
    br = BufferedReader(InputStreamReader(input_stream2));
    pw = PrintWriter(input_socket2.getOutputStream,true);
    pw.println('noop')
    br.read
end

Any ideas?

+1  A: 

Since you didn't provide the actual error, it is difficult to pinpoint the problem.

Anyways, here's a simple implementation to show the concept (tested and working just fine!):

Server.java

import java.net.*;
import java.io.*;

public class Server
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Listening on port...");
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }

        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
            System.out.println("Received connection!");
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()) );
        String inputLine;

        while ( (inputLine = in.readLine()) != null ) {
            System.out.println("Client says: " + inputLine);
            out.println(inputLine);
        }

        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}

Client.m

import java.io.*;
import java.net.*;

%# connect to server
try
    sock = Socket('localhost',4444);
    in = BufferedReader(InputStreamReader(sock.getInputStream));
    out = PrintWriter(sock.getOutputStream,true);
catch ME
    error(ME.identifier, 'Connection Error: %s', ME.message)
end

%# get input from user, and send to server
userInput = input('? ', 's');
out.println(userInput);

%# get response from server
str = in.readLine();
disp(['Server says: ' char(str)])

%# cleanup
out.close();
in.close();
sock.close();
Amro
A: 

Hi everyone,

Thanks for all the help! Thinking about things more and reading your comments helped me get to the right answer! Amro, your code is great but I can't implement the Java code because the program I'm trying to communicate with isn't something I've written - it's a program called c-gate and it's a program that can control the Clipsal Square D lighting system. The type of commands it takes are of the form "on 254/56/26" - this turns on the light specified by this path.

So for all those who're curious about how my final code looks like:

function message = client(host, port, number_of_retries)

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.io.; import java.util.;

if (nargin < 3)
    number_of_retries = -1; % set to -1 for infinite
end

retry        = 0;
input_socket = [];
message      = [];

while true

    retry = retry + 1;
    if ((number_of_retries > 0) && (retry > number_of_retries))
        fprintf(1, 'Too many retries\n');
        break;
    end

    try
        fprintf(1, 'Retry %d connecting to %s:%d\n', ...
                retry, host, port);

        % throws if unable to connect
        input_socket = Socket(host, port);

        % get a buffered data input stream from the socket
        input_stream   = input_socket.getInputStream;
        d_input_stream = DataInputStream(input_stream);

        fprintf(1, 'Connected to server\n');

        % read data from the socket - wait a short time first
        pause(0.5);
        bytes_available = input_stream.available;
        fprintf(1, 'Reading %d bytes\n', bytes_available);

        message = zeros(1, bytes_available, 'uint8');
        for i = 1:bytes_available
            message(i) = d_input_stream.readByte;
        end

        message = char(message);

        % cleanup
        input_socket.close;
        break;

    catch
        if ~isempty(input_socket)
            input_socket.close;
        end

        % pause before retrying
        pause(1);
    end
end

% set up a socket between client and c-gate
host2        = 'localhost';
port2        = 20023;

try
    input_socket2 = Socket(host2,port2);
    input_stream2   = input_socket2.getInputStream;
    d_input_stream2 = DataInputStream(input_stream2);
    br = BufferedReader(InputStreamReader(input_stream2));
    pw = PrintWriter(input_socket2.getOutputStream,true);
    read = readLine(br)
    disp('I read the line')
    pw.println('get 254/56/26 level')
    disp('I entered the command')
    read2 = readLine(br)
end

end

Thanks again!

Justine