简体   繁体   中英

python echo server does not work

I am trying to implement simple echo-server using python. Here is my code taken from different internet sourses:

#!/usr/bin/python

import socket

host = "192.168.253.134"
port = 33333

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5)
print "Server on {server}:{port} is running...".format(server=host, port=port)
sock, addr = s.accept()

while True:
    buffer = sock.recv(128)
    if buffer == 'exit':
        sock.send("bye")
        break
    elif buffer:
        sock.send(buffer)

sock.close()
print "Server is closed..." 

The problem is that when I connect to the server and type exit , server does not close connection but echo me back my own query((( I noticed that buffer is actually "exit\\n" but combinations like "exit\\n" do not work((( I do not see the problem. It seems that this code works but not on my ubuntu(((

The line break (also known as newline ) gets sent as well, so fix using strip to remove the line break ( \\n ):

while True:
    buffer = sock.recv(128)
    if buffer.strip() == 'exit':
        sock.send("bye")
        break
    elif buffer:
        sock.send(buffer)

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