簡體   English   中英

Python套接字如何處理客戶端意外關閉

[英]Python sockets how to handle the client closing unexpectedly

我的python套接字服務器偵聽,然后連接到客戶端,該客戶端將隨后從用戶發送不確定數量的字符串。 然后,客戶端可能會關閉或失去與服務器的連接。

這會導致錯誤。

[Errno 10053]主機中的軟件中斷了已建立的連接。 或[Errno 10054]現有連接被遠程主機強行關閉

如何處理此事件,以便可以關閉連接並重新啟動服務器以偵聽重新連接?

Python Server示例:

# Echo server program
import socket
import sys

HOST = None               # Symbolic name meaning all available interfaces
PORT = 7001              # Arbitrary non-privileged port
s = None

def startListening():
    print "starting to listen"

    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                  socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error as msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)
    conn, addr = s.accept()
    print 'Connected by', addr
    while 1:
        data = conn.recv(1024)
        if not data: 
            break
        print data
        message = ""
        while not "quit" in message:
            message = raw_input('Say Something : ')
            conn.sendall(message)
        #conn.send("I got that, over!")

    conn.close()
    print "connection closed"

while 1:
    startListening()

python客戶端示例:

# Echo client program
import socket
import sys

HOST = 'localhost'    # The remote host
PORT = 7001              # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except socket.error as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except socket.error as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print 'could not open socket'
    sys.exit(1)
s.sendall("Please send me some strings")
data = ""
while ("quit" not in data):
    data = s.recv(1024)
    print 'Received', repr(data)
s.close()

要重現此錯誤,請在一個命令窗口中運行服務器,然后在第二個命令窗口中運行客戶端,然后關閉客戶端窗口。

添加try:例外:服務器腳本中的數據發送和數據接收周圍出現,以緩解該問題:

# Echo server program
import socket
import sys

HOST = None               # Symbolic name meaning all available interfaces
PORT = 7001              # Arbitrary non-privileged port
s = None

def startListening():
    print "starting to listen"

    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                  socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error as msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)
    conn, addr = s.accept()
    print 'Connected by', addr
    while 1:
        try: 
            data = conn.recv(1024)
        except:
            print "cannot recieve data"
            break
        if not data: 
            break
        print data
        message = ""
        while not "quit" in message:
            message = raw_input('Say Something : ')
            try: 
                conn.sendall(message)
            except Exception as exc:
                #print exc # or something.
                print "message could not be sent"
                break
        #conn.send("I got that, over!")

    conn.close()
    print "connection closed"

while 1:
    startListening()

只需關閉連接側並准備好再次接受新連接即可。

解決此問題的最佳方法是將服務器套接字的創建和accept / read / write循環分開:

create_server_socket()
while True:
    accept_new_connection();
    try:
        read_request();
        write_response()
    finally:
        close_connection()

我認為,當客戶端意外關閉時,根據SIGPIPE,您應該處理信號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM