Reputation: 45
I'm fairly new to Python. I have two scripts running that are communicating with each other, but once the sender process stops sending bytes, the receiver process receives an endless stream of what decodes (UTF-8) to new lines. I've reduced the code as much as I could to keep things simple:
Sender Python script.
import socket
s = socket.socket()
host = "127.0.0.1"
port = 5409
s.bind((host, port))
data_to_send = ['1','2','3','4','5','6','7','8','9']
s.listen(1)
c, addr = s.accept()
print ('Got connection from ', addr,'. Sending data...', sep='')
for data in data_to_send:
message = data.encode('utf-8')
c.sendall(message)
Receiver Python script.
import socket
messages_received = 0
s = socket.socket()
host = "127.0.0.1"
port = 5409
s.connect((host, port))
while True:
incoming_message = s.recv(1024).decode('utf-8')
messages_received += 1
# This condition is just to avoid printing thousands of lines
if messages_received < 10:
print(messages_received, ':', incoming_message)
Receiver output.
1 : 1
2 : 23456789
3 :
4 :
5 :
6 :
7 :
8 :
9 :
What am I doing wrong? I would ideally want the sender script to break out of the "While True" loop if the socket closes.
Upvotes: 0
Views: 1248
Reputation: 45
As @jasonharper pointed out, all I needed to do was to check for empty messages and break the loop as soon as that happens. When the sender doesn't send anything, the receiver doesn't receive empty massages, it just waits for a valid message, which I didn't know. The following code worked for me:
Sender Python script.
import socket
import time
s = socket.socket()
host = "127.0.0.1"
port = 5409
s.bind((host, port))
data_to_send = ['1','2','3','4','5','6','7','8','9']
s.listen(1)
c, addr = s.accept()
print ('Got connection from ', addr,'. Sending data...', sep='')
for data in data_to_send:
message = data.encode('utf-8')
c.sendall(message)
time.sleep(1)
Receiver Python script.
import socket
messages_received = 0
s = socket.socket()
host = "127.0.0.1"
port = 5409
s.connect((host, port))
while True:
incoming_message = s.recv(1024).decode('utf-8')
messages_received += 1
if not incoming_message:
break
if messages_received < 10:
print(messages_received, ':', incoming_message)
Receiver output.
1 : 1
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 8
9 : 9
Upvotes: 1
Reputation:
well you can try setting the buffer size on sender side : socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024) # Buffer size 1024
if it dosent work you can try even dict format so you send data as json format.
Upvotes: 0