客户端关闭时服务器崩溃

Pac*_*aco 2 python sockets networking client-server

我今天早些时候遇到过这个问题.这是我的第一个网络应用程序.

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()
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

它是一个非常基本的客户端/服务器应用程序 服务器启动,等待客户端发送命令.客户端连接到服务器,要求用户键入命令.然后将命令发送到回复<command> received或的服务器Invalid 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
Run Code Online (Sandbox Code Playgroud)

在服务器端:

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
Run Code Online (Sandbox Code Playgroud)

Mar*_*nen 5

把你accept放在一个循环中.就像是:

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 
Run Code Online (Sandbox Code Playgroud)

另请注意,recv当客户端关闭连接时返回空字符串,因此if not content: break.