Python socket.recv() 返回新行?

Python socket.recv() returning new lines?

我是 Python 的新手。我有两个相互通信的脚本 运行,但是一旦发送方进程停止发送字节,接收方进程就会收到源源不断的解码 (UTF-8) 到新行的流。为了简单起见,我尽可能地减少了代码:

发件人 Python 脚本。

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)

接收者 Python 脚本。

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)

接收器输出。

1 : 1
2 : 23456789
3 : 
4 :
5 :
6 :
7 :
8 :
9 :

我做错了什么?理想情况下,如果套接字关闭,我希望发件人脚本跳出“While True”循环。

好吧,您可以尝试在发件人端设置缓冲区大小: socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024) # 缓冲区大小 1024

如果它不起作用,您甚至可以尝试使用 dict 格式,以便以 json 格式发送数据。

正如@jasonharper 指出的那样,我需要做的就是检查是否有空消息,并在出现空消息时立即中断循环。当发送者不发送任何东西时,接收者不会收到空消息,它只是等待有效消息,我不知道。以下代码对我有用:

发件人 Python 脚本。

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)

接收者 Python 脚本。

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)

接收器输出。

1 : 1
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 8
9 : 9