numpy-using-socket icon indicating copy to clipboard operation
numpy-using-socket copied to clipboard

alternate class, inspired by your work

Open amarco opened this issue 1 year ago • 1 comments

I created the class below, it essential does the same thing but it is bidirectional and I pass dictinaries back and forth which can contain numpy arrays, strings ect. Do with as you may.

import socket import pickle import struct import logging

class SocketDataTransfer(): def init(self): logging.info("Instantiating object") self.address = '' self.port = 0 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.type = None self.data =b''

def initialize(self,address,port,mode,buffSize=16):
    """
    :initialize
    :param address: host address of the socket e.g 'localhost' or your ip
    :type address: str
    :param port: port in which the socket should be intialized. e.g 4000
    :type port: int
    :param mode: instatntiate mode of operation [ client | server ]
    :type mode: str
    :return: None
    :rtype: None
    """
    self.address = address
    self.port = port
    self.mode = mode.lower()
    self.buffSize = buffSize
    self.payload_size = struct.calcsize("!Q")  
    logging.info("Attempting to Initializing mode: {0}".format(self.mode))
    if self.mode == "client":
        self.initialize_sender()
    elif self.mode == "server":
        self.initalize_receiver()

def initialize_sender(self):
    """
    :acts as client
    :param address: host address of the socket e.g 'localhost' or your ip
    :type address: str
    :param port: port in which the socket should be intialized. e.g 4000
    :type port: int
    :return: None
    :rtype: None
    """
    logging.info("Initializing client mode connection to:{0}:{1}".format(self.address, self.port))
    self.socket.connect((self.address, self.port))
    logging.info("..client mode complete")

def initalize_receiver(self):
    """
    :acts as server
    :param port: port to listen
    :type port: int
    :return: numpy array
    :rtype: ndarray
    """
    logging.info("Initializing server mode")
    self.socket.bind((self.address, self.port))
    logging.info("..waiting for connection")
    self.socket.listen(10)
    self.conn, addr = self.socket.accept()
    logging.info("..incoming connection from: {0}:{1}".format(addr,self.port))
    

def send_data(self, data):
    """
    :param np_array: Numpy array to send to the listening socket
    :type np_array: ndarray
    :return: None
    :rtype: None
    """
    if self.mode == "client":
        conn = self.socket
    elif self.mode == "server":
        conn = self.conn

    _data = pickle.dumps(data)
    message_size = struct.pack("!Q", len(_data))  
    conn.sendall(message_size + _data)

def receive_data(self):

    if self.mode == "client":
        conn = self.socket
    elif self.mode == "server":
        conn = self.conn

    while len(self.data) < self.payload_size:
        packet = conn.recv(self.buffSize)
        if not packet: break
        self.data += packet
        
    packed_msg_size = self.data[:self.payload_size]
    self.data = self.data[self.payload_size:]
    msg_size = struct.unpack("!Q", packed_msg_size)[0]

    # Retrieve all data based on message size
    while len(self.data) < msg_size:
        packet = conn.recv(self.buffSize)
        if not packet: break
        self.data += packet

    frame_data = self.data[:msg_size]
    self.data = self.data[msg_size:]

    # Extract frame
    _data = pickle.loads(frame_data)
    return _data

amarco avatar Mar 19 '23 00:03 amarco

Hi @amarco , Thanks, mind sending a PR, this could be useful for others as well.

Thank you again!

vaghawan avatar Mar 20 '23 12:03 vaghawan