在Matlab中编写Java代码?

时间:2010-04-20 13:51:08

标签: java sockets matlab

我正在尝试在Matlab中使用Java命令pw.println()和br.readLine(),因为我在Matlab和我想要使用Java类控制的命令行程序之间设置了一个套接字(input_socket2) BufferedReader和PrintWriter。在下面的代码片段之前,我在两台计算机之间实现了另一个套接字。这很好用,我也知道下面的代码片段成功地打开了Matlab和其他程序之间的通信线路。但是,Matlab在pw.println('noop')处抛出错误。我认为它与语法有关,但我不确定如何用Matlab语法编写命令:

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

有什么想法吗?

2 个答案:

答案 0 :(得分:7)

由于您未提供实际错误,因此很难确定问题。

无论如何,这是一个简单的实现来展示这个概念(经过测试和正常工作!):<​​/ p>

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

答案 1 :(得分:0)

感谢您的帮助!更多地思考和阅读你的评论帮助我找到了正确的答案! Amro,你的代码很棒,但是我无法实现Java代码,因为我试图与之通信的程序不是我写的东西 - 它是一个叫做c-gate的程序,它是一个可以控制Clipsal的程序方D照明系统。它采用的命令类型为“on 254/56/26” - 这将打开此路径指定的灯光。

所以那些对我的最终代码看起来很好奇的人:

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

再次感谢!