Jan-14-2020, 08:40 AM
(This post was last modified: Jan-14-2020, 08:40 AM by Gribouillis.)
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 clientOutput:Client received: b'hello world\n'
Exiting Client