通过Python客户端与java服务器通信
问题描述:
我想调整一个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;
}
}
答
如果你想在Python中发送一个字符串:
在python2你可以做sock.send(s)
其中s
是你想发送和sock
是socket.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."
确保import
socket
,sys
和struct
谢谢!像冠军一样工作,实际上从服务器获得了一些东西,认为它实际上是一个错误信息,但比我得到的更好。还有一个send_string的快速修正应该是[发送:]而不是[发送:] – enderv
@enderv啊,是的,谢谢你的更正。很高兴它的工作。如果有更具体的东西需要帮助,可以编辑原始帖子并让我知道。 –