2017-07-25 34 views
0

我使用Python編寫chatbot程序。當它收到一條消息時,它會計算要說的話並返回一條消息。如何連接Python chatbot和Java聊天室

我的朋友使用Java編寫聊天室。這是一個平常的聊天室,但是當人類發送消息時,這會將其發送給聊天機器人。

如何連接它們?他們在同一臺PC上運行,不使用互聯網。

+0

將此用作參考:[將數據從python發送到JAVA](https://stackoverflow.com/questions/41406672/send-data-from-python-program-to-java-程序),使用套接字進行進程間通信[Socket](https://jj09.net/interprocess-communication-python-java/) –

回答

1

你可以使用運行時類來完成。示例代碼:

public String sendMessage(String message) throws IOException { 
    Runtime rt = Runtime.getRuntime(); 
    Process proc = rt.exec("python /Users/user/bot.py " + message); 

    BufferedReader stdInput = new BufferedReader(new 
      InputStreamReader(proc.getInputStream())); 

    BufferedReader stdError = new BufferedReader(new 
      InputStreamReader(proc.getErrorStream())); 

    // read the output from the command 
    String s = null; 
    StringBuilder answer = new StringBuilder(); 
    while ((s = stdInput.readLine()) != null) { 
     answer.append(s); 
    } 

    return answer.toString(); 
}