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啊,是的,謝謝你的更正。很高興它的工作。如果有更具體的東西需要幫助,可以編輯原始帖子並讓我知道。 –