python echo server - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Networking (https://python-forum.io/forum-12.html) +--- Thread: python echo server (/thread-23720.html) |
python echo server - kerzol81 - Jan-14-2020 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? RE: python echo server - Gribouillis - Jan-14-2020 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 and the output from the client
RE: python echo server - codexcotechnologies - Jan-16-2020 Thank you for the information. |