Last active
October 5, 2023 09:48
-
-
Save zsrinivas/ab71ea72d726e72847f1 to your computer and use it in GitHub Desktop.
Simple Telnet Echo Server and Telnet Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('-') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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