问题描述
这段代码有问题.我正在打开一个套接字,然后用一个 while 循环来监听它.我从 php 脚本发送数据
I have a problem here with this code. I'm opening a socket, then listening to it with a while loop. I send data from a php script with
socket_write($sock, $test, $len);
它工作得很好,但是当我连续发送多个写入时,Python 脚本将一些写入处理为一次写入.
It works very well, but when I send several writes in a row, the Python script handles some of the writes as just one write.
import socket
HOST = 'localhost' # the host
PORT = 12126 # the port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
while 1:
s.listen(0)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.close()
我正在寻找一种方法来监听该端口并获得一个接一个的写入.
I'm looking for a way to listen to that port and get one write after another.
推荐答案
这不是套接字的工作方式.字节输入和字节输出,但必须有一些其他机制来告诉您消息有多大.如果您在套接字的一端发送 50 个字节,然后再发送 75 个字节,然后是 20 个字节,然后调用 recv(100),则您可以从阻塞套接字中获取 1 到 100 个字节的任何值.你负责缓冲recv,直到你有一个完整的消息,你必须定义一个完整的消息是什么.一些选项:
That's not the way sockets work. Bytes go in and bytes come out, but there has to be some other mechanism to tell you how big a message is. If you send 50 bytes, then another 75 bytes, then 20 bytes on one end of a socket, and then call recv(100), you could get anywhere from 1 to 100 bytes from a blocking socket. You are responsible for buffering recv's until you have a complete message, and you have to define what a complete message is. Some options:
- 发送固定长度的消息.
- 发送代表消息长度的固定字节数,然后是消息.
- 用标记字节分隔消息.
这是一个使用标记字节缓冲接收到的数据的类的示例:
Here's an example of a class to buffer received data using a sentinel byte:
import socket
class Client(object):
def __init__(self):
self.buffer = ''
self.sock = None
def connect(self,address):
self.buffer = ''
self.sock = socket.socket()
self.sock.connect(address)
def get_msg(self):
'''Append raw data to buffer until sentinel is found,
then strip off the message, leaving the remainder
in the buffer.
'''
while not '
' in self.buffer:
data = self.sock.recv(4096)
if not data:
return ''
self.buffer += data
sentinel = self.buffer.index('
') + 1
msg,self.buffer = self.buffer[:sentinel],self.buffer[sentinel:]
return msg
def close(self):
self.sock.close()
if __name__ == '__main__':
c = Client()
c.connect((HOST,PORT))
while True:
msg = c.get_msg()
if not msg:
break
print repr(msg)
c.close()
这篇关于多个写入作为单个处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!