Bottom Page

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?
Quote
#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
kerzol81 likes this post
Quote
#3
Thank you for the information.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)