通过python客户端与java服务器通信
我正在尝试调整示例java代码以使API能够与python脚本一起工作。我知道java代码可以工作,并且可以在python中进行套接字连接,但我不知道如何在python中转换字符串以成功发送xml请求。我很确定我需要使用struct,但上个星期我还没弄明白 此外,我相当确定我需要先发送请求的长度,然后再发送请求,但我仍然无法在服务器程序上获得任何显示成功请求的内容通过python客户端与java服务器通信,java,python,sockets,client-server,Java,Python,Sockets,Client Server,我正在尝试调整示例java代码以使API能够与python脚本一起工作。我知道java代码可以工作,并且可以在python中进行套接字连接,但我不知道如何在python中转换字符串以成功发送xml请求。我很确定我需要使用struct,但上个星期我还没弄明白 此外,我相当确定我需要先发送请求的长度,然后再发送请求,但我仍然无法在服务器程序上获得任何显示成功请求的内容 public void connect(String host, int port) { try { set
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
是要发送的字符串,sock
是一个socket.socket
。在python3中,需要将字符串转换为bytestring。您可以使用字节(s,'utf-8')进行转换,也可以像b'abcd'中那样在字符串前面加上b。请注意,发送仍然具有套接字发送的所有正常限制,即它将只发送尽可能多的数据,并返回经过的字节数
以下内容将用作具有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."
def发送请求(self,xml\u字符串):
send_string=struct.pack('i',len(xml_string))+xml_string
大小=长度(发送字符串)
已发送=0
发送时<大小:
尝试:
sent+=self.sock.send(发送字符串[sent:])
除socket.error外:
打印>>sys.stderr,“与服务器的连接已断开。”
打破
其他:
打印“已发送请求”
确保导入
套接字
,系统
,以及结构
谢谢!像一个冠军一样工作,实际上从服务器上得到了一些东西,认为这实际上是一条错误消息,但总比我什么都没有得到要好。另外,send_字符串中的一个快速更正应该是[send:]而不是[send:]@enderv啊,是的,谢谢您的更正。很高兴它起作用了。如果有更具体的事情需要你的帮助,你可以编辑你原来的文章,让我知道。