0
我想调整一个API的示例java代码来使用python脚本。我知道java代码的工作原理,并可以在python中执行套接字连接,但无法弄清楚如何将python中的字符串转换为能够成功发送xml请求。我很确定我需要使用struct,但是在上周还没有弄清楚。通过Python客户端与java服务器通信
另外我很确定我需要先发送请求的长度然后再发送请求,但是我再一次没有能够获得任何东西来显示服务器程序上的成功请求。
public void connect(String host, int port) {
try {
setServerSocket(new Socket(host, port));
setOutputStream(new DataOutputStream(getServerSocket().getOutputStream()));
setInputStream(new DataInputStream(getServerSocket().getInputStream()));
System.out.println("Connection established.");
} catch (IOException e) {
System.out.println("Unable to connect to the server.");
System.exit(1);
}
}
public void disconnect() {
try {
getOutputStream().close();
getInputStream().close();
getServerSocket().close();
} catch (IOException e) {
// do nothing, the program is closing
}
}
/**
* Sends the xml request to the server to be processed.
* @param xml the request to send to the server
* @return the response from the server
*/
public String sendRequest(String xml) {
byte[] bytes = xml.getBytes();
int size = bytes.length;
try {
getOutputStream().writeInt(size);
getOutputStream().write(bytes);
getOutputStream().flush();
System.out.println("Request sent.");
return listenMode();
} catch (IOException e) {
System.out.println("The connection to the server was lost.");
return null;
}
}
谢谢!像冠军一样工作,实际上从服务器获得了一些东西,认为它实际上是一个错误信息,但比我得到的更好。还有一个send_string的快速修正应该是[发送:]而不是[发送:] – enderv
@enderv啊,是的,谢谢你的更正。很高兴它的工作。如果有更具体的东西需要帮助,可以编辑原始帖子并让我知道。 –