目前,我在使用基本套接字服務器時遇到問題。本質上,我無法控制此服務器的客戶端,并且客戶端正在發送由一組已知字符分隔的未知長度的 XML 訊息。這個問題的基本再現可以通過以下方式進行演示,
import socket
server_address = ('192.168.2.47', 10000)
#server
#client
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
sock.send('<messageBody><ew32f/><dwadwa/></messageBody>')
sock.send('<messageBody><dwaaw/><fewwfe/></messageBody>')
sock.send('<messageBody><ewqf3x/><awdwad2/></messageBody>')
# the socket will stay connected so long as the client continues sending data which could be days or more
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(server_address)
client, addr = sock.accept(1)
# I need to find a way to receive the client data such that it stops receiving the the </messageBody> tag
我試圖找到最有效的方法來解決這個問題,因為服務器每秒可能會從各種客戶端接收數百條訊息。這些訊息的大小可能在幾個位元組到幾千位元組之間。
uj5u.com熱心網友回復:
我認為 Python 的 expat 決議器可以幫助你;它允許流式決議,并且塊可以是 XML 的片段(如bar下面的示例所示)。
我很確定我理解您的問題及其背景關系。這是我嘗試顯示您的服務器接收此示例 XML:
<root>
<foo />
<bar />
<messageBody>
<ewqf3x />
<awdwad2 />
</messageBody>
<baz />
</root>
但是以塊為單位,就好像客戶端通過多次呼叫向您提供整個 XML 主體一樣。每個塊都被決議,當<messageBody/>讀取結束標記時,會引發一個錯誤,這是您擁有所需的一切并且可以停止處理(收聽?)的信號。
#!/usr/bin/env python3
import sys
from xml.parsers.expat import ParserCreate
class FoundMessageBodyEnd(Exception):
pass
def end_element(name):
print(f'Processing end-tag for {name}')
if name == 'messageBody':
# This may not be the right way to do this
raise FoundMessageBodyEnd
p = ParserCreate()
p.EndElementHandler = end_element
streaming_chunks = [
'''<root>
<foo />
<bar ''', # notice that bar is not closed till the first line of the next chunk
'''/>
<messageBody>
<ewqf3x />
<awdwad2 />''',
''' </messageBody>''',
''' <baz />
</root>''',
]
parsed = 0
for chunk in streaming_chunks:
try:
p.Parse(chunk)
parsed = 1
except FoundMessageBodyEnd:
print(f'After parsing {parsed 1} chunks, found messageBody delimiter, done.')
sys.exit(1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/398778.html
上一篇:從圓串列中回傳最小的圓
