我有一個Java服務器和Python客戶端之間的TCP連接。 當'q'從任何到其他連接發送時必須關閉。 它發揮作用,當我從Python發送'q'到Java。然而,當我從java發送'q'到python時,它不起作用。我嘗試了類型轉換但沒用。TCP Java服務器,Python客戶端字符串不等於
Java服務器:
公共類發件人{
public static void main(String[] args) throws IOException {
String fromclient;
ServerSocket Server = new ServerSocket(25000);
System.out.println("TCPServer Waiting for client on port 25000");
while (true) {
Socket connected = Server.accept();
System.out.println(
" THE CLIENT" + " " + connected.getInetAddress() + ":" + connected.getPort() + " IS CONNECTED ");
PrintWriter out = new PrintWriter(connected.getOutputStream(), true);
Scanner sc = new Scanner(System.in);
while (true) {
String input = sc.nextLine();
out.println(input);
}
}
}
}
Python客戶端:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 25000))
while True:
r, _, _ = select.select([client_socket], [], [])
if r:
data = client_socket.recv(4096)
string_data = data.decode('utf-8')
print str(string_data) == 'q'
if str(string_data) == 'q' or string_data == 'Q':
print ('Connection closed')
client_socket.close()
break
else:
print (string_data)
聲明打印STR(string_data)== 'Q' 總是返回假
仍然是同樣的問題 –
找出java端使用Charset.defaultCharset()或系統屬性或InputStreamReader.getEncoding編碼並使用相同的python端 – Shiva
的編碼是UTF-8 –