2

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

ovod
  • 1,118
  • 4
  • 18
  • 33

1 Answers1

2

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)
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • Depending on the client, the line ending sent might even be a `\r\n`. Telnet for example, even on Unix, sends `\r\n` (see [RFC1123](https://tools.ietf.org/html/rfc1123#page-21)). So that might be the reason why the OP's attempt to test for `exit\n` still didn't match. – Lukas Graf Dec 17 '14 at 00:13
  • I think `strip` handles all "whitespace" characters. This means it handles both forms of line endings. – Reut Sharabani Dec 17 '14 at 00:18
  • 1
    Yes, that's exactly why it's the perfect solution, hence the upvote ;-) – Lukas Graf Dec 17 '14 at 00:19
  • Ah, ok, thought you had a better one :) – Reut Sharabani Dec 17 '14 at 00:23