Reputation: 364
I have three files. client.py, server.py and test.py. client.py is below:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 6088))
while True:
a = raw_input()
s.send(a)
s.close()
server.py:
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1',6088))
s.listen(1)
print("Waitting for connection.....")
while True:
socket,addr = s.accept()
while True:
data = socket.recv(1024)
if data:
print(data)
s.close()
test.py:
while True:
a = raw_input()
print("welcom "+ a)
I use server.py
or test.py
to start the server, then I use the client.py
to start the client, but when I am inputting something in client, the server doesn't show anything. Why? And how to fix it.
Upvotes: 2
Views: 2999
Reputation: 73
Assuming you don't want to turn off buffering completely (this could cause inefficiencies in other parts of the code), just call sys.stdout.flush() after each print statement in server.py.
Upvotes: 0
Reputation: 123531
By default the output from Python is buffered for performance reasons unless stdout goes to a terminal. This means any output from print
will not be send immediately to the pipe but will first be buffered inside the Python process and only send if enough data have accumulated in the buffer. To switch this off and make any output be send immediately to the pipe use python -u
or similar.
Note that this behavior is not unique to Python. Other commands (like perl) show a similar behavior.
Upvotes: 3