Python套接字发送速度比接收器快

时间:2017-07-06 09:42:58

标签: python python-2.7 sockets

所以,我有一台服务器使用socket.send()方法向客户端发送响应。有时在localhost上测试代码,当客户端连续两次使用socket.send()时,客户端用来接收服务器响应的socket.recv()方法会在一个中获取两个不同的消息。 例如: 服务器:

from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 13005
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
connection_socket, client_ip = serverSocket.accept()
connection_socket.send('Message one')
connection_socket.send('Message two')

客户端:

from socket import *

serverName = 'localhost'
serverPort = 13005
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
print clientSocket.recv(1024)
print clientSocket.recv(1024)

随机运行客户端的结果是

Message oneMessage two

除非我在两个send()之间放一个睡眠(0.1)。有没有办法避免使用睡眠?我是否需要在recv()方法中输入要接收的确切字节数?

1 个答案:

答案 0 :(得分:3)

TCP是面向流的协议,不会逐个发送消息。分割消息的简单方法,您可以在消息末尾设置分割字符串,如\r\n

示例:

客户端:

#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 13005

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send('Message one\r\n')
s.send('Message two\r\n')
s.close()

服务器:

#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 13005
BUFFER_SIZE = 20  # Normally 1024, but we want test

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
data = ''
while 1:
    data += conn.recv(BUFFER_SIZE)
    if not data: break
    if not data.endswith('\r\n'):
        continue
    lines = data.split('\r\n')
    for line in lines:
        print line
    data = ''
conn.close()

如果您的邮件很复杂且很长,您可以看到:Python Socket Receive Large Amount of Data