I'm playing around with socket programming in Python 2 and trying out select() for the server script. When I have the following code for the server:
print('Server started in port {}.'.format(self.port))
server_socket = socket.socket()
server_socket.bind((self.address, self.port))
server_socket.listen(5)
client_sockets = [server_socket]
while True:
for s in client_sockets:
if s is server_socket:
client_socket, address = server_socket.accept()
client_sockets.append(client_socket)
print('Connection received.')
else:
data = s.recv(200)
if data:
print('Received: {}'.format(data.decode().strip()))
else:
client_sockets.remove(s)
s.close()
The server only receives the first message from the client. However, the second and later messages will only be received when the client is restarted. This baffles me (of which I attribute to my inadequate knowledge in networking). The data seems to be buffered. Why does this happen?
I did try this:
client_sockets = [server_socket]
while True:
readable, writable, errored = select.select(client_sockets, [], [])
for s in readable:
if s is server_socket:
...
And finally, the server can now receive the second and later messages from the client.
Here is the code for the client:
class BasicClient(object):
def __init__(self, name, address, port):
self.name = name
self.address = address
self.port = int(port)
self.socket = socket.socket()
def connect(self):
self.socket.connect((self.address, self.port))
self.socket.send(self.name)
def send_message(self, message):
self.socket.send(message.encode())
args = sys.argv
if len(args) != 4:
print "Please supply a name, server address, and port."
sys.exit()
client = BasicClient(args[1], args[2], args[3])
client.connect()
while True:
message = raw_input('Message: ')
# We pad the message by 200 since we only expect messages to be
# 200 characters long.
num_space_pads = min(200 - len(message), 200)
message = message.ljust(num_space_pads, ' ')
client.send_message(message)
sendcall could be broken up and the receiver needing multiple calls torecvto receive all. Or that more than onesendcould be received in a singlerecv. And the last could include partial "messages".