Skip to content

Instantly share code, notes, and snippets.

@zsrinivas
Last active October 5, 2023 09:48
Show Gist options
  • Save zsrinivas/ab71ea72d726e72847f1 to your computer and use it in GitHub Desktop.
Save zsrinivas/ab71ea72d726e72847f1 to your computer and use it in GitHub Desktop.
Simple Telnet Echo Server and Telnet Client
import telnetlib
HOST = "localhost"
PORT = 8080
tn = telnetlib.Telnet(HOST, PORT)
for x in xrange(100):
tn.write(str(x) + '\n')
tn.write('-')
print tn.read_until('-')
import socket, threading
lock = threading.Lock()
clients = [] #list of clients connected
class TelnetServer(threading.Thread):
def __init__(self, (sock, address)):
threading.Thread.__init__(self)
self.socket = sock
self.address = address
def run(self):
lock.acquire()
clients.append(self)
lock.release()
print '%s:%s connected.' % self.address
while True: # continously read data
data = self.socket.recv(1024)
if not data:
break
for c in clients:
c.socket.send(data)
self.socket.close()
print '%s:%s disconnected.' % self.address
lock.acquire()
clients.remove(self)
lock.release()
def main():
HOST = '127.0.0.1'
PORT = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
while True: # multiple connections
TelnetServer(s.accept()).start()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment