Created
May 3, 2019 02:02
-
-
Save sixem/a66b976a90fde5fbb20bc222fc3e9fc9 to your computer and use it in GitHub Desktop.
Python TCP Class Example
This file contains 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 datetime | |
import socket | |
class TCP(object): | |
def __init__(self): | |
self.TCPClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
def closeTCPConnection(self): | |
self.TCPClient.close() | |
def establishTCPConnection(self, HostIp, HostPort): | |
self.TCPClient.connect((HostIp, HostPort)) | |
def sendTCPLog(self, message): | |
timestamp = datetime.datetime.fromtimestamp(int(time.time())).strftime('%H:%M:%S') | |
data = "{}: {} \n".format(timestamp, message) | |
try: | |
self.TCPClient.sendall(data.encode()) | |
received = self.TCPClient.recv(1024) | |
except Exception as e: | |
print(e) | |
#Usage | |
#Initialize class and establish connection | |
TCPClass = TCP() | |
TCPClass.establishTCPConnection("192.168.1.106", 6500) | |
#Send some messages | |
TCPClass.sendTCPLog("This is a simple test") | |
TCPClass.sendTCPLog("And this is another test") | |
#Close the connection | |
TCPClass.closeTCPConnection() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment