Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中检测断开连接,而不发送数据_Python_Sockets_Logging_Exception Handling_Disconnect - Fatal编程技术网

如何在python中检测断开连接,而不发送数据

如何在python中检测断开连接,而不发送数据,python,sockets,logging,exception-handling,disconnect,Python,Sockets,Logging,Exception Handling,Disconnect,好的,我有一个插座,我一次处理一行并记录它。下面的代码非常适用于此。cout函数是我用来向日志发送数据的函数。我使用for循环,以便一次只能处理一行 socket.connect((host, port)) readbuffer = "" while True: readbuffer = readbuffer+socket.recv(4096).decode("UTF-8") cout("RECEIVING: " + readbuffer) #Logs the buffer

好的,我有一个插座,我一次处理一行并记录它。下面的代码非常适用于此。cout函数是我用来向日志发送数据的函数。我使用for循环,以便一次只能处理一行

socket.connect((host, port))
readbuffer = ""
while True:
    readbuffer = readbuffer+socket.recv(4096).decode("UTF-8")
    cout("RECEIVING: " + readbuffer) #Logs the buffer
    temp = str.split(readbuffer, "\n")
    readbuffer=temp.pop( )
    for line in temp:
        #Handle one line at a time.
我遇到了一个问题,当服务器断开我的连接时,突然我有一个巨大的文件,上面写满了“RECEIVING:”。我知道这是因为当python套接字断开连接时,套接字开始不断地接收空白数据

我尝试插入:

if "" == readbuffer:
    print("It disconnected!")
    break
所做的一切就是立即中断循环,并说它断开了连接,即使连接成功

我还知道,我可以通过发送数据来检测断开连接,但我不能这样做,因为我发送的任何内容都会被广播到服务器上的所有其他客户端,这意味着要调试这些客户端,所以我认为它会干扰


我该怎么办。高级版谢谢。

您需要将
recv()
的结果单独检查到readbuffer

while True:
  c = socket.recv(4096)
  if c == '': break # no more data
  readbuffer = readbuffer + c.decode("UTF-8")
  ...

string.split
还是
str.split
?因为我看不到导入或
str
标识符。
str.split('hello\nworld','\n')
可以,如果有点非常规的话-只调用
str
内置的unbound方法,而不是
'hello\nworld'
对象的绑定方法。注意,您不能总是检测(突然的)除非您愿意使用keep-alive(或超时),否则断开连接而不进行书写。这对于TCP来说是非常普遍的,与语言无关(请参阅)。非常感谢您的帮助。现在我看到了,这是我的一个重大进步:P。