简体   繁体   English

客户端关闭时服务器崩溃

[英]Server crashes when the client is closing

I have encountered this problem earlier today. 我今天早些时候遇到过这个问题。 This is my first network application. 这是我的第一个网络应用程序。

server.py 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 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()

It is a very basic client/server application. 它是一个非常基本的客户端/服务器应用程序 The server starts up, and wait for the client to send commands. 服务器启动,并等待客户端发送命令。 The client connects to the server, asks the user to type a command. 客户端连接到服务器,要求用户键入命令。 Commands are then sent to the server which replies <command> received or Invalid command . 然后将命令发送到服务器,该服务器回复<command> received Invalid commandInvalid command The code was running fine, until I hit CTRL + C . 代码运行良好,直到我按下CTRL + C为止。 The server crashed. 服务器崩溃了。 Why is that ? 这是为什么 ?

Example: 例:

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

On the server side: 在服务器端:

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

Put your accept in a while loop, too. 把你的accept放在一个while循环中。 Something like: 就像是:

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 

Also note recv returns empty string when the client closes the connection, hence the if not content: break . 另请注意,当客户端关闭连接时, recv返回空字符串,因此if not content: break

Basically, I wasn't recreating a new connection on my server for new future clients, and then, when it was hitting the line conn.send('Invalid command') , it was crashing. 基本上,我没有在我的服务器上为新的未来客户端重新创建新连接,然后,当它遇到conn.send('Invalid command')conn.send('Invalid command') ,它崩溃了。 To solve this: 要解决这个问题:

I just replaced: 我刚换了:

conn.send('Invalid command')

with: 有:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过套接字关闭服务器时通知客户端 - Notify client when closing server via socket 在 python 客户端中关闭与 kube.netes API 服务器的客户端连接 - Closing client connection to kubernetes API server in python client 关闭客户端 - Closing a client 从服务器执行时,Python脚本崩溃 - Python script crashes when executed from server 从exe运行时,Python http反向Shell客户端崩溃 - Python http reverse shell client crashes when run from exe 当另一个客户端连接到服务器时客户端断开连接 - Client disconnects when another client connects to the server 使用qt4agg运行matplotlib后关闭时,Python脚本由于导入而崩溃 - Python script crashes when closing after running matplotlib with qt4agg because of import 聊天室服务器未关闭线程且在SIGINT时未退出 - chat-room server not closing threads and not exiting when SIGINT python 客户端中的 Sockets 在多连接服务器中的事件读写事件后未关闭 - Sockets in python client not closing after event read write events in multi-connection server recv 命令在线程和服务器崩溃时无法正常工作 - The recv command does not work as it should when threading and the server crashes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM