gpt4 book ai didi

Python客户端服务器通信

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

我试图将一些数据从服务器发送到客户端,但客户端没有获取所有数据。

服务器:

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 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:
print "Unexpected error:", sys.exc_info()[0]

我哪里出错了?

最佳答案

使用 TCP 时,读取与写入不对称,通常接收操作系统返回的数据 block 比发送方发送的数据 block 小得多。常见的解决方案是为每次发送添加一个固定大小的整数作为前缀,该整数包含下一条消息的长度。接收完整消息的模式变为:

bin  = sock.recv(4) # for 4-byte integer
mlen = struct.unpack('I', bin)[0]
msg = ''
while len(msg) != mlen:
chunk = sock.recv(4096) # 4096 is an arbitrary buffer size
if not chunk:
raise Exception("Connection lost")
msg += chunk

关于Python客户端服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6370683/

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