Last active
January 2, 2019 22:12
-
-
Save glinders/d43beaf8b11d01dcc69163fded523a6d to your computer and use it in GitHub Desktop.
Interactive TCP client using threads
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
#!/usr/bin/env python | |
import socket | |
import sys | |
import os | |
import multiprocessing | |
TCP_IP = '192.168.1.100' | |
TCP_PORT = 8234 | |
BUFFER_SIZE = 8192 | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.connect((TCP_IP, TCP_PORT)) | |
class SendThread(multiprocessing.Process): | |
def __init__(self, group=None, target=None, name=None, | |
args=(), kwargs=None, verbose=None): | |
super(SendThread, self).__init__() | |
self.target = target | |
self.name = name | |
def run(self): | |
# stdin is closed by multiprocessing, so open it again | |
sys.stdin = os.fdopen(0) | |
while True: | |
line = sys.stdin.readline() | |
if len(line) > 0: | |
# quit, if we receive escape-q | |
if line.startswith('\x1bq'): | |
return | |
s.send('{}\r'.format(line)) | |
class ReceiveThread(multiprocessing.Process): | |
def __init__(self, group=None, target=None, name=None, | |
args=(), kwargs=None, verbose=None): | |
super(ReceiveThread, self).__init__() | |
self.target = target | |
self.name = name | |
return | |
def run(self): | |
while True: | |
data = s.recv(BUFFER_SIZE) | |
if data: | |
print('{}'.format(data)) | |
if __name__ == '__main__': | |
sender = SendThread(name='sender') | |
receiver = ReceiveThread(name='receiver') | |
sender.start() | |
receiver.start() | |
sender.join() | |
receiver.terminate() | |
s.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment