简体   繁体   中英

Server crashes when the client is closing

I have encountered this problem earlier today. This is my first network application.

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()

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 . The code was running fine, until I hit 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. 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 .

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. To solve this:

I just replaced:

conn.send('Invalid command')

with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM