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.