Python Forum

Full Version: python echo server
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I commited this little echo server for testing purposes. The only thing I don't like, that I cannot stop or exit from the client side.
I'd like to break the while loop if the client sends a 'q' or 'quit'.

import socket
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = 'localhost'
port = 2323

try:
    s.bind((ip, port))
except OSError:
    print("error")

print("[*] Server started, port {}".format(port))

s.listen(1)
conn, client_ip = s.accept()

while 1:
    print('[*] Connected client: {}'.format(client_ip))
    conn.send(b'AAAA:BBBB,018:233,CCCC:DDDD\n')
    time.sleep(1)

conn.close()
Could you please help me?
I don't see the 'echo' part in your code. Here is a slightly modified version that receives lines of text from the client and send them back.
import socket
import time
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = 'localhost'
port = 2323
 
try:
    s.bind((ip, port))
except OSError:
    print("error")
 
print("[*] Server started, port {}".format(port))
 
s.listen(1)
conn, client_ip = s.accept()
 
print('[*] Connected client: {}'.format(client_ip))
with conn.makefile(encoding='utf8') as ifh:
    for line in ifh:
        print('Server received:', repr(line))
        if line.strip() == 'q':
            break
        else:
            conn.sendall(line.encode())
 
conn.close()
print('Exiting server.')
Here is a rudimentary client code. All this is only a starting point. I strongly suggest the use of the selectors module to handle the task of waiting for sockets to be ready
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = 'localhost'
port = 2323
 
s.connect((ip, port))
s.send('hello world\n'.encode())
print('Client received:', s.recv(1024))
s.send('q\n'.encode())
print('Exiting Client')
Here is the output written by the server
Output:
[*] Server started, port 2323 [*] Connected client: ('127.0.0.1', 52116) Server received: 'hello world\n' Server received: 'q\n' Exiting server.
and the output from the client
Output:
Client received: b'hello world\n' Exiting Client
Thank you for the information.