Skip to content

Instantly share code, notes, and snippets.

@GluTbl
Created July 2, 2020 05:18
Show Gist options
  • Save GluTbl/b373fdf7bca3ecf9e6494ec0cd3ede6a to your computer and use it in GitHub Desktop.
Save GluTbl/b373fdf7bca3ecf9e6494ec0cd3ede6a to your computer and use it in GitHub Desktop.
TcpServer
import socket
import threading
from time import sleep
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
print('Listening : ' + str(socket.gethostbyname(socket.gethostname())) + ': ' + str(self.port))
self.connect = True
self.client = None
def disconnect(self):
# self.sock.shutdown(socket.SHUT_RDWR)
self.connect = False
if (self.client is not None):
print('Cleint closed')
self.client.close()
self.sock.close()
print('Diconnected...')
def stopsock(self):
client = socket.socket(socket.AF_INET,
socket.SOCK_STREAM) # we wan to close the .accept alse so we mock connection
client.connect(("127.0.0.1", self.port))
def listen(self):
self.sock.listen(5)
self.connect = True
while (self.connect):
self.client, address = self.sock.accept()
self.client.settimeout(60)
threading.Thread(target=self.listenToClient, args=(self.client, address)).start()
def listenToClient(self, client, address):
size = 1024
response = b""
if (self.connect == False):
client.close()
print('Plugin is closed')
return
#print(address)
while (True):
try:
data = client.recv(size)
if b'\r\n' in data:
response = response + data
client.send(b"echo: "+response)#Here we send response back
client.close()
break
if data:
# Set the response to echo back the recieved data
response = response + data
else:
response = response + data
client.close()
break
except:
client.close()
break
client.close()
##here we got the message
#print("Already closed")
print(response)
server=ThreadedServer("0.0.0.0",2222)
server.listen()
while True:
sleep(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment