问题描述
我正在做一个应该与Python Server通信的简单Java客户端应用程序。我可以轻松地将字符串发送到Python Server并在控制台中打印它,但是当我尝试在IF中使用接收到的字符串时,即使应该,也永远不会进入IF语句。
I am doing a simple Java Client application which should communicate with Python Server. I can easily send a string to Python Server and print it in console, but when i'm trying to use received string in IFs it never get into IF statement even if it should.
这是Java客户端发送msg代码
Here is Java Client send msg code
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
if(msgToServer != null){
dataOutputStream.writeUTF("UP");
}
System.out.println(dataInputStream.readLine());
Python服务器代码:
And Python Server code:
import socket
HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
print 'Socket now listening'
conn, addr = s.accept()
print 'Connected to: ' + addr[0] + ':' + str(addr[1])
data = conn.recv(1024)
if data == "UP":
conn.sendall('Works')
else:
conn.sendall('Does not work')
conn.close()
s.close()
print data
因此,当我发送到 UP的Python服务器时,它应该发送回Java Client Works,但是我显示不起作用,并且在Python Server中输出数据是: UP
So when i send to Python Server "UP" it should send back to Java Client "Works", but i reveive "Does not work" and in Python Server the output data is: "UP"
为什么if语句不加入?
Why it isn't go into if statement?
推荐答案
说:
The JavaDoc of DataOutputStream#writeUTF(...)
says:
在python代码中,您的 data
值将以两个字节作为前缀要跟随的字符串。
In you python code your data
value will be prefixed with two bytes for the length of the string to follow.
这篇关于与Python(服务器)通信的Java(客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!