2017-01-08 121 views
0

所以我用socket.connec是連接到IRC聊天Python36和插座

我經由socket.send通過我的變量登錄

的登錄成功,然後我坐在了一會兒使用 Socket.recv(1024)

如果我只是不斷打印響應一切看起來不錯,但讓我們說我想添加到字符串的末尾......我注意到,socket.recv不總是得到完整的消息(只能達到預期的1024),並且消息的剩餘部分在循環的下一次迭代中。

這使得它無法逐行處理反饋。

有沒有更好的方式來不斷讀取數據而不會中斷數據?是否可以在收到響應之前計算出響應的大小,以便可以動態設置緩衝區?

回答

0

TCP是基於流的協議。緩衝接收到的字節並僅從流中提取完整的消息。

有關完整行,請在緩衝區中查找換行符。

例服務器:

import socket 

class Client: 

    def __init__(self,socket): 
     self.socket = socket 
     self.buffer = b'' 

    def getline(self): 
     # if there is no complete line in buffer, 
     # add to buffer until there is one. 
     while b'\n' not in self.buffer: 
      data = self.socket.recv(1024) 
      if not data: 
       # socket was closed 
       return '' 
      self.buffer += data 

     # break the buffer on the first newline. 
     # note: partition(n) return "left of n","n","right of n" 
     line,newline,self.buffer = self.buffer.partition(b'\n') 
     return line + newline 

srv = socket.socket() 
srv.bind(('',5000)) 
srv.listen(1) 
conn,where = srv.accept() 
client = Client(conn) 
print(f'Client connected on {where}') 
while True: 
    line = client.getline() 
    if not line: 
     break 
    print(line) 

實施例的客戶端:

s=socket() 
s.connect(('127.0.0.1',5000)) 
s.sendall(b'line one\nline two\nline three\nincomplete') 
s.close() 

在服務器輸出:

Client connected on ('127.0.0.1', 2667) 
b'line one\n' 
b'line two\n' 
b'line three\n' 
+0

試圖檢查每一行,看它是否與結束\ n或結尾\ r或以\ r \ n結尾,但沒有任何一行是。即使是完整的。在解碼utf-8之前和之後嘗試檢查。我想知道是否我的.splitlines()方法正在消除換行符 –

+0

@AntonioAnonymous是的,'.splitlines()'移除了換行符。你必須緩衝,直到你有一個換行符,然後處理緩衝區。我會用一個例子來更新。 –