简体   繁体   中英

Can' t find condition to stop simple telnet server on python

I want to create simple server. But condition for closing of connection by server isn't satisfies.

import socket
soc = socket.socket()
soc.bind(('', 33333))
soc.listen(2)
(conn, address) = soc.accept()
while True:
    data = conn.recv(1024)
    conn.sendall(data)
    if(data == 'stop'):
        conn.close()
        break

Ubuntu bash after running of this code:

~$ telnet localhost 33333
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stop
stop

The variable data actually equals to 'stop\\r\\n' .

Use str.strip to remove the line terminator:

if data.strip() == 'stop':

EDIT: Consider acquiring data using:

data = ''
while not data.endswith('\n'):
    data += conn.recv(1024)

You might also want to read the Socket Programming HOWTO from the official documentation.

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