Python socket server and pipe

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.pyto start the client, but when I am inputting something in client, the server doesn't show anything. Why? And how to fix it.

1 answer

  • answered 2018-07-11 05:21 Steffen Ullrich

    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.