2016-08-28 13:43:00 +02:00
|
|
|
# Python rough implementation of a C# TCP client
|
2016-08-26 12:58:53 +02:00
|
|
|
import socket
|
2016-09-07 19:48:49 +02:00
|
|
|
from utils import BinaryWriter
|
2016-08-26 12:58:53 +02:00
|
|
|
|
|
|
|
|
|
|
|
class TcpClient:
|
|
|
|
def __init__(self):
|
|
|
|
self.connected = False
|
|
|
|
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
|
|
|
|
def connect(self, ip, port):
|
2016-08-28 13:43:00 +02:00
|
|
|
"""Connects to the specified IP and port number"""
|
2016-08-26 12:58:53 +02:00
|
|
|
self.socket.connect((ip, port))
|
2016-09-03 10:54:58 +02:00
|
|
|
self.connected = True
|
2016-08-26 12:58:53 +02:00
|
|
|
|
|
|
|
def close(self):
|
2016-08-28 13:43:00 +02:00
|
|
|
"""Closes the connection"""
|
2016-08-26 12:58:53 +02:00
|
|
|
self.socket.close()
|
2016-09-03 10:54:58 +02:00
|
|
|
self.connected = False
|
2016-08-26 12:58:53 +02:00
|
|
|
|
|
|
|
def write(self, data):
|
2016-08-28 13:43:00 +02:00
|
|
|
"""Writes (sends) the specified bytes to the connected peer"""
|
2016-09-05 18:35:12 +02:00
|
|
|
self.socket.sendall(data)
|
2016-08-26 12:58:53 +02:00
|
|
|
|
|
|
|
def read(self, buffer_size):
|
2016-08-28 13:43:00 +02:00
|
|
|
"""Reads (receives) the specified bytes from the connected peer"""
|
2016-09-07 19:48:49 +02:00
|
|
|
with BinaryWriter() as writer:
|
|
|
|
while writer.written_count < buffer_size:
|
|
|
|
# When receiving from the socket, we may not receive all the data at once
|
|
|
|
# This is why we need to keep checking to make sure that we receive it all
|
|
|
|
left_count = buffer_size - writer.written_count
|
|
|
|
partial = self.socket.recv(left_count)
|
|
|
|
writer.write(partial)
|
2016-09-06 18:54:49 +02:00
|
|
|
|
2016-09-07 19:48:49 +02:00
|
|
|
return writer.get_bytes()
|