2013-05-16 2 views
0

파이썬 스크립트로 작동하는 API의 샘플 자바 코드를 조정하려고합니다. Java 코드가 작동하고 파이썬에서 소켓 연결을 수행 할 수 있지만 xml 요청을 성공적으로 보낼 수 있도록 파이썬에서 문자열을 변환하는 방법을 알아낼 수는 없습니다. 구조체를 사용해야하지만 지난 주에 아직 이해할 수 없었다고 확신합니다.은 파이썬 클라이언트를 통해 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

당신이 파이썬에서 문자열을 보내려고하는 경우 : s 당신이 보내 싶어하고 socksocket.socket되는 문자열입니다 python2에서

은 그냥 sock.send(s) 할 수 있습니다. python3에서 문자열을 바이트로 변환해야합니다. 바이트 (s, 'utf-8')를 사용하여 변환하거나 b'abcd '에서와 같이 b에 문자열 앞에 접두사를 붙일 수 있습니다. send는 여전히 소켓 전송의 모든 일반적인 제한 사항을 가지고 있습니다. 즉, 가능한 한 많이 보내고 얼마나 많은 바이트가 통과했는지 계산합니다.

다음은 sock 특성을 가진 클래스의 메서드로 작동합니다. sockimportsocket, sys

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." 

이 있는지 확인

을 통해 보낼 수있는 소켓되고, 그리고 struct

+0

감사합니다! 실제로 챔피언처럼 일한 것은 실제로 서버에서 뭔가를 얻었지만 실제로는 오류 메시지가 아니라 내가 얻은 것보다 낫다고 생각합니다. 또한 send_string의 빠른 교정은 [send :] 대신 [sent :]가되어야합니다. – enderv

+0

@enderv 예, 수정 해 주셔서 감사합니다. 다행 했어. 좀 더 구체적인 것이 있으면이 도움말을 통해 도움을 받아야합니다. 원래 게시물을 편집하고 알려 주시기 바랍니다. –

관련 문제