gpt4 book ai didi

Python丢包

转载 作者:行者123 更新时间:2023-12-01 06:09:59 24 4
gpt4 key购买 nike

我尝试用Python编写一个客户端服务器应用程序,但我遇到了一个问题,在客户端我没有获取所有发送的数据。首先我尝试发送数字1到10,我收到了1,2,5,6,10,所以丢失了很多数字。

服务器端:

def __init__( self ):
super( MCCommunication, self ).__init__()

HOST, PORT = socket.gethostbyname( socket.gethostname() ), 31000
self.server = SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )
ip, port = self.server.server_address
# Start a thread with the server
# Future task: Make the server a QT-Thread...
self.server_thread = threading.Thread( target = self.server.serve_forever )
# Exit the server thread when the main thread terminates
self.server_thread.setDaemon( True )
self.textUpdated.emit( 'Server Started!' )
print( 'Server Started!' )
self.server_thread.start()

def handle( self ):
#self.request.setblocking( 0 )
i = 10;
while True:
if( self.clientname == 'MasterClient' ):
try:
#ans = self.request.recv( 4096 )
#print( 'after recv' )
""" Sendign data, testing purpose """
while i:
mess = str( i );
postbox['MasterClient'].put( self.creatMessage( 0, 0 , mess ) )
i = i - 1

while( postbox['MasterClient'].empty() != True ):
sendData = postbox['MasterClient'].get_nowait()

a = self.request.send( sendData )
print( a );
#dic = self.getMessage( sendData )
#print 'Sent:%s\n' % str( dic )
except:
mess = str( sys.exc_info()[0] )
postbox['MasterClient'].put( self.creatMessage( 1, 0 , mess ) )
pass

def creatMessage( self, type1 = 0, type2 = 0, message = ' ', extra = 0 ):
return pickle.dumps( {"type1":type1, "type2":type2, "message":message, "extra":extra} );

其中 postbox['MasterClient'] 是一个包含序列化消息的队列。

这是客户端:

def run( self ):        
sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
addr = ( self.ip, self.port )
#print addr
sock.connect( addr )
#sock.setblocking( 0 )
while True:
try:
ans = sock.recv( 4096 )
dic = self.getMessage( ans )
self.recvMessageHandler( dic )
print 'Received:%s\n' % str( dic )
except:
pass

最佳答案

当客户端尝试读取消息时,服务器可能已发送多条消息,如果这些消息适契约(Contract)一个 4k 缓冲区,则 recv() 调用将获取这两条消息。

你没有显示getMessage代码,但我猜你正在做pickle.loads(msg)之类的事情,但这只会给你第一条消息并丢弃字符串的其余部分,因此丢弃了消息。如果您阅读时缓冲的字节数超过 4096 个字节,您还会遇到另一个问题,因为您最终可能会收到消息的片段,从而出现 unpickling 错误。

您需要将返回的字符串分解为单独的消息,或者更好的是,只需将套接字视为流并让 pickle.load 从中提取一条消息。

关于Python丢包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6384900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com