簡體   English   中英

客戶端關閉時服務器崩潰

[英]Server crashes when the client is closing

我今天早些時候遇到過這個問題。 這是我的第一個網絡應用程序。

server.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket

s = socket.socket()
host = socket.gethostname()

# Reserve a port for your service.
port = 12345
# Bind to the port
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))

# Now wait for client connection.
s.listen(1)
conn, addr = s.accept()
try:
    while True:
        # connection, address
        content = conn.recv(1024)
        if content in ('status', 'stop', 'start', 'reload', 'restart'):
            conn.send('%s received' % content)
        else:
            conn.send('Invalid command')
except KeyboardInterrupt:
    conn.close()
    s.shutdown(socket.SHUT_RDWR)
    s.close()

client.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket

s = socket.socket()
host = socket.gethostname()
port = 12345

s.connect((host, port))
try:
    while True:
        print ''
        value = raw_input('Enter a command:\n')
        if value != '':
            s.send(value)
            print s.recv(1024)
except KeyboardInterrupt:
    s.shutdown(socket.SHUT_RDWR)
    s.close()

它是一個非常基本的客戶端/服務器應用程序 服務器啟動,並等待客戶端發送命令。 客戶端連接到服務器,要求用戶鍵入命令。 然后將命令發送到服務器,該服務器回復<command> received Invalid commandInvalid command 代碼運行良好,直到我按下CTRL + C為止。 服務器崩潰了。 這是為什么 ?

例:

python client.py 

Enter a command:
stop
stop received

Enter a command:
status
status received

Enter a command:
bla
Invalid command

Enter a command:
^C

在服務器端:

python server.py 
Traceback (most recent call last):
  File "server.py", line 25, in <module>
    conn.send('Invalid command')
socket.error: [Errno 32] Broken pipe

把你的accept放在一個while循環中。 就像是:

while True:
    conn, addr = s.accept()        # accept one connection.
    while True:                    # Receive until client closes.
        content = conn.recv(1024)  # waits to receive something.
        if not content:            # Receive nothing? client closed connection,
            break                  #   so exit loop to close connection.
        if content in ('status', 'stop', 'start', 'reload', 'restart'):
            conn.send('%s received' % content)
        else:
            conn.send('Invalid command')
    conn.close()                   # close the connection 

另請注意,當客戶端關閉連接時, recv返回空字符串,因此if not content: break

基本上,我沒有在我的服務器上為新的未來客戶端重新創建新連接,然后,當它遇到conn.send('Invalid command')conn.send('Invalid command') ,它崩潰了。 要解決這個問題:

我剛換了:

conn.send('Invalid command')

有:

try:
    conn.send('Invalid command')
except socket.error:
    conn, addr = s.accept()

暫無
暫無

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

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