I've wrote two programs to test this p23_server.py for the server side and p23_client.py for the client side :
p23_server.py
#p23_server.py
import socket
HOST = '10.0.2.15'
PORT = 12345
server = socket.socket()
server.bind((HOST,PORT))
server.listen(1)
(client,addr) = server.accept()
while True:
data = client.recv(32)
if not data:
break
print(data.decode('utf-8'))
server.close()
p23_client.py
#p23_client.py
import socket
import sys
HOST = '10.0.2.15'
PORT = 12345
string = sys.argv[1]
data_to_send = string.encode('utf-8')
s = socket.socket()
s.connect((HOST,PORT))
#s.sendall(data_to_send)
s.send(data_to_send)
s.close()
I run the p23_server.py and then executed the command :
wahalez@wahalez:~/dev/python$ python p23_client.py $(python -c 'for i in range(1024): print("a",end="")')
to run the client side and look at what the server outputs.
I executed it once with the socket.send() and once with the socket.sendall() function. The results are the same. The question is why ? shouldn't send just send the data once and the server receive the 32 bytes and that's it ?
Unlike send(), this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.
Why both of the functions produce the same result ?
just because 99% of the time send() will manage to send all the data in 1 go. Theoretically, when you use send(), you might not see all the data on the server.
To emphasize the difference, a sample pseudo implementation of sendall:
def sendall(data):
already_sent = 0
while already_sent < len(data):
already_sent += send(data[already_sent:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With