Reputation: 385
I have a TCP connection between a Java server and Python Client. when 'q' is sent from any to the other connection must be closed. It works when I send 'q' from python to java. However, when I sent 'q' from java to python it does not work. I tried typecasting but no use.
Java Server:
public class Sender {
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:
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)
The statement print str(string_data) == 'q' always returns false
Upvotes: 1
Views: 303
Reputation: 22983
You need to change your Java server code from out.println(input)
to out.print(input)
. Add also an out.flush()
to force that the data are send immediately not only after the buffer is filled.
println
- would also send the linebreak to the client
With print
it works as expected.
edit Some additonal. In such a case it helps on the Python client to print out the bytes in data
.
Amend the Python client code as
data = client_socket.recv(4096)
for i in bytearray(data):
sys.stdout.write(hex(i) + " ")
print
Assumed input on Java is q+ENTER
. See below the output on the Pathon client side.
using on Java server side out.println
0x71 0xd 0xa
False
q
using on Java server side out.print
0x71
True
Connection closed
That way it's easy to spot the additional bytes (0xd 0xa
) which were sent to the client.
Upvotes: 2
Reputation: 32
I think the encoding is the problem. Just comment out the encoding part and the code should work.
Upvotes: -1