Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python echo server
#1
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?
Reply
#2
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
Reply
#3
Thank you for the information.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Paramiko Server -- Exception (server): Error reading SSH protocol banner ujlain 3 4,281 Jul-24-2023, 06:52 AM
Last Post: Gribouillis
  sending packet onto dummy network device but receiving echo sabuzaki 2 1,412 Feb-12-2023, 10:31 AM
Last Post: Vadanane

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020