Writing Java's pw.println(), etc. in MATLAB

前端 未结 2 598
清酒与你
清酒与你 2020-12-10 22:38

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 wan

2条回答
  •  囚心锁ツ
    2020-12-10 23:32

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

提交回复
热议问题