I am working on socket programming.Here server sends random number of bytes to the machine who connected to server.This random number simulate that server is also receving data from somwhere else and data length can vary much and we are not sure how much.
I am running a server and client both on the same machine. I was expecting no data loss, but to my surprise I can see data loss is happening here too. I must be doing something wrong in my code. I have tried to find but I didn't found anything suspicious. I can just guess the length of data may be a problem, however still I am not sure.
From the server I am first sending the length of the message to the client and then sending the actual message so that I can be sure I have received complete message.
I am connecting to server 100 times and many times the data loss is happening.
Below is my server code:
import socket
import struct
import random as rand
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a specific address and port
server_address = ('localhost', 12345)
sock.bind(server_address)
sock.listen(1)
while True:
message = "12345" * rand.randint(100000, 200000)
connection, client_address = sock.accept()
message_in_bytes=message.encode()
length = len(message_in_bytes)
print(client_address, "connected and message length is ",length)
length_bytes = struct.pack("<I", length)
connection.send(length_bytes + message_in_bytes)
connection.close()
Below is client code:
import socket
import struct
def connect_server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 12345)
sock.connect(server_address)
message_length_bytes=sock.recv(4)
length_of_message = struct.unpack("<I",message_length_bytes)[0]
whole_message=sock.recv(length_of_message)
sock.close()
if length_of_message == len(whole_message):
return "success"
else:
return "failed"
stats={'success':0,'failed':0}
for _ in range(100):
stats[connect_server()] +=1
print(stats)