2016-08-28 14:43:00 +03:00
|
|
|
# Python rough implementation of a C# TCP client
|
2016-08-26 13:58:53 +03:00
|
|
|
import socket
|
|
|
|
|
|
|
|
|
|
|
|
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 14:43:00 +03:00
|
|
|
"""Connects to the specified IP and port number"""
|
2016-08-26 13:58:53 +03:00
|
|
|
self.socket.connect((ip, port))
|
2016-09-03 11:54:58 +03:00
|
|
|
self.connected = True
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def close(self):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Closes the connection"""
|
2016-08-26 13:58:53 +03:00
|
|
|
self.socket.close()
|
2016-09-03 11:54:58 +03:00
|
|
|
self.connected = False
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def write(self, data):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Writes (sends) the specified bytes to the connected peer"""
|
2016-09-05 19:35:12 +03:00
|
|
|
self.socket.sendall(data)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def read(self, buffer_size):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Reads (receives) the specified bytes from the connected peer"""
|
2016-09-06 19:54:49 +03:00
|
|
|
# TODO improve (don't cast to list, use a mutable byte list instead or similar, see recv_into)
|
|
|
|
result = []
|
|
|
|
while len(result) < buffer_size:
|
|
|
|
left_data = buffer_size - len(result)
|
|
|
|
partial = self.socket.recv(left_data)
|
|
|
|
result.extend(list(partial))
|
|
|
|
|
|
|
|
return bytes(result)
|