2013-05-16 114 views
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; 
    } 
} 

回答

0

如果你想在Python中發送一個字符串:

在python2你可以做sock.send(s)其中s是你想發送和socksocket.socket的字符串。在python3中,您需要將字符串轉換爲字符串。你可以使用字節(s,'utf-8')進行轉換,或者在b前面加上一個b作爲b'abcd'。請注意,發送仍具有套接字發送的所有正常限制,即它只會發送儘可能多的數據,並返回有多少字節經過的計數。

以下將作爲具有sock屬性的類的方法工作。 sock是插座通過

發送
def send_request(self, xml_string): 
    send_string = struct.pack('i', len(xml_string)) + xml_string 
    size = len(send_string) 
    sent = 0 
    while sent < size: 
     try: 
      sent += self.sock.send(send_string[sent:]) 
     except socket.error: 
      print >> sys.stderr, "The connection to the server was lost." 
      break 
    else: 
     print "Request sent." 

確保importsocketsysstruct

+0

謝謝!像冠軍一樣工作,實際上從服務器獲得了一些東西,認爲它實際上是一個錯誤信息,但比我得到的更好。還有一個send_string的快速修正應該是[發送:]而不是[發送:] – enderv

+0

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