2017-07-25 31 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(); 
}