예제 #1
0
 def __init__(self,db):
   self._ipcPath=db.getSettingPath()
   SocketlikeIPC.__init__(self, self._ipcPath)
   # super(type(self),self).__init__(self._ipcPath)
   # if super(type(self),self)._connect():
   if SocketlikeIPC._connect(self):
     print('IPC connect succeed. Welcome back, administrator.')
     return
   print('IPC failed. proceeding with TCP.')
   super(type(self)) #unbound
   socket.__init__(self)
   try:
     socket.connect(self,('racu.idea.sh', PortEnum.MAIN_SERVER.value))
     lastPin = db.getConfig()
     print('lastPin =', lastPin, len(lastPin))
     pinmsg = int.to_bytes(SocketEnum.PIN.value, 1, 'big') + int.to_bytes(lastPin[0]) if 10**3<=lastPin['lastPIN']<10**4 else b''
     msg = ''
     # while not msg:
     socket.sendall(self,pinmsg)
     msg = socket.recv(self)
     if not msg:
       print('main server connect error')
       return
   except:
     print('main server connect error')
예제 #2
0
 def __init__(self, db):
     self._ipcPath = db.getSettingPath()
     SocketlikeIPC.__init__(self, self._ipcPath)
     # super(type(self),self).__init__(self._ipcPath)
     # if super(type(self),self)._connect():
     if SocketlikeIPC._connect(self):
         print('IPC connect succeed. Welcome back, administrator.')
         return
     print('IPC failed. proceeding with TCP.')
     super(type(self))  #unbound
     socket.__init__(self)
     try:
         socket.connect(self, ('racu.idea.sh', PortEnum.MAIN_SERVER.value))
         lastPin = db.getConfig()
         print('lastPin =', lastPin, len(lastPin))
         pinmsg = int.to_bytes(
             SocketEnum.PIN.value, 1, 'big') + int.to_bytes(
                 lastPin[0]) if 10**3 <= lastPin['lastPIN'] < 10**4 else b''
         msg = ''
         # while not msg:
         socket.sendall(self, pinmsg)
         msg = socket.recv(self)
         if not msg:
             print('main server connect error')
             return
     except:
         print('main server connect error')
예제 #3
0
 def broadcast_data(self, sock, message):
     for socket in self._connection_list:
         if socket != self.sock and socket != sock:
             try:
                 socket.sendall(message)
             except OSError:
                 socket.close()
                 self._connection_list.remove(socket)
예제 #4
0
def sendPacket(socket, tag="", data=""):
    packetLength = 2 + 8 + len(data)
    packet = pack(">H", packetLength)
    packet += tag.ljust(8, "\0")
    packet += data
    try:
        socket.sendall(packet)
    except Exception as e:
        print e.strerror
        sys.exit(1)
예제 #5
0
def echo_client(sock, client_addr):
    print("Got connection from", client_addr)

    while True:
        msg = socket.recv(65536)
        if not msg:
            break

        socket.sendall(msg)
    print('Client closed connection')
    socket.close()
예제 #6
0
def receive_messages(client_addr):
    while True:
        messages_received = client_addr.recv(256)
        if not messages_received:
            break
        last_received_message = messages_received.decode('utf-8')
        for client in Clients:
            socket, (ip, port) = client
            if socket is not client_addr:
                socket.sendall(last_received_message.encode('utf-8'))
    client_addr.close()
예제 #7
0
def sendPacket(socket, tag="", data=""):
    # Determine packet length.
    packetLength = 2 + TAG_LEN + len(data)

    # Build packet.
    packet = pack(">H", packetLength)
    packet += tag.ljust(TAG_LEN, "\0")
    packet += data

    # Send packet to the server.
    try:
        socket.sendall(packet)
    except Exception as e:
        print e.strerror
        sys.exit(1)
예제 #8
0
파일: ftclient.py 프로젝트: wilsonsk/cs372
def sendPack(socket, tag = "", data = ""):
    # Determine packet length.
    packetLength = 2 + TAG_LEN + len(data)

    # Build packet.
    packet = pack(">H", packetLength)
    packet += tag.ljust(TAG_LEN, "\0")
    packet += data

    # Send packet to the server.
    try:
        socket.sendall(packet)
    except Exception as e:
        print e.strerror
        sys.exit(1)
def sendPacket(socket, handle, message):
    # Determine message packet length.
    packetLength = 2 + HANDLE_SIZE + len(message)

    # Build the message packet.
    packet = pack('>H', packetLength)
    packet += handle.ljust(HANDLE_SIZE, '\0')
    packet += message

    # Send message packet to the server.
    try:
        socket.sendall(packet)
    except Exception as e:
        print e.strerror
        sys.exit(1)
예제 #10
0
def ssl_sendall(self, data, flags=0):
    self._checkClosed()

    if self._sslobj:
        if flags != 0:
            raise ValueError(
                "non-zero flags not allowed in calls to sendall() on %s" %
                self.__class__)
        amount = len(data)
        done = count = 0
        start = time.time()

        io = BytesIO(data)
        while True:
            count += 1

            # calc current rate
            now = time.time()
            elapsed = now - start
            rate = float(done) / elapsed
            if rate > RATE:
                time.sleep(0.5)
                continue

            chunk = io.read(CHUNK_SIZE)
            if chunk:
                self.send(chunk)
                done += len(chunk)
                if count % 15 == 0:
                    stats.record_fileprogress(done, amount)
            else:
                break
        return amount
    else:
        return socket.sendall(self, data, flags)
예제 #11
0
def ssl_sendall(self, data, flags=0):
    self._checkClosed()

    if self._sslobj:
        if flags != 0:
            raise ValueError(
                "non-zero flags not allowed in calls to sendall() on %s" %
                self.__class__)
        amount = len(data)
        done = count = 0
        start = time.time()

        io = BytesIO(data)
        while True:
            count += 1

            # calc current rate
            now = time.time()
            elapsed = now - start
            rate = float(done) / elapsed
            if rate > RATE:
                time.sleep(0.5)
                continue

            chunk = io.read(CHUNK_SIZE)
            if chunk:
                self.send(chunk)
                done += len(chunk)
                if count % 15 == 0:
                    stats.record_fileprogress(done, amount)
            else:
                break
        return amount
    else:
        return socket.sendall(self, data, flags)
def makeRequest(socket, tag = "", data = ""):
    # calculate the packet length, data + tag(8 bytes) + length bytes(2 bytes)
    packetLength = 2 + 8 + len(data)

    # construct the packet
	# sources: https://docs.python.org/2/library/struct.html
	# http://www.tutorialspoint.com/python/string_ljust.htm
    packet = pack(">H", packetLength)
    packet += tag.ljust(8, "\0")
    packet += data

    # send packet to server
	# https://docs.python.org/2/tutorial/errors.html
    try:
        socket.sendall(packet)
    except Exception as e:
        print e.strerror
        sys.exit(1)
def client_handler(self, conn, address, conn_list, server):
    conn_time = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M')
    print(f'New connection at {conn_time}')
    print(f'{address} has been connected.')
    conn_establish = True
    #1024 is buffersize , after connection and conn_establish = true, get message from client and decode in utf-8
    while conn_establish:
        message = conn.recv(1024).decode('utf-8')
        #if client didn't send any messages break this function and rerun
        if not message:
            break
        #for clients in conn_list if socket is not server , then send message to all(broadcast)
    for conn in conn_list:
        if socket != server.socket:
            try:
                socket.sendall(message)
                #if client disconect socket close then remove client from conn_list
            except:
                socket.close()
                conn_list.remove(socket)
예제 #14
0
 def sendall(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         amount = len(data)
         count = 0
         while (count < amount):
             v = self.send(data[count:])
             count += v
         return amount
     else:
         return socket.sendall(self, data, flags)
예제 #15
0
 def sendall(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         amount = len(data)
         count = 0
         while (count < amount):
             v = self.send(data[count:])
             count += v
         return amount
     else:
         return socket.sendall(self, data, flags)
예제 #16
0
 def sendall(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         if flags != 0:
             raise ValueError('non-zero flags not allowed in calls to sendall() on %s' % self.__class__)
         amount = len(data)
         count = 0
         while count < amount:
             v = self.send(data[count:])
             count += v
         return amount
     return socket.sendall(self, data, flags)
예제 #17
0
 def sendall(self, data, flags=0):
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         amount = len(data)
         count = 0
         while (count < amount):
             v = self.send(data[count:])
             count += v
         return amount
     else:
         return socket.sendall(self, data, flags)
예제 #18
0
파일: ssl.py 프로젝트: KrishMunot/pyston
 def sendall(self, data, flags=0):
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         amount = len(data)
         count = 0
         while (count < amount):
             v = self.send(data[count:])
             count += v
         return amount
     else:
         return socket.sendall(self, data, flags)
예제 #19
0
파일: ssl.py 프로젝트: 1st1/cpython
 def sendall(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         count = 0
         with memoryview(data) as view, view.cast("B") as byte_view:
             amount = len(byte_view)
             while count < amount:
                 v = self.send(byte_view[count:])
                 count += v
     else:
         return socket.sendall(self, data, flags)
예제 #20
0
 def sendall(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         count = 0
         with memoryview(data) as view, view.cast("B") as byte_view:
             amount = len(byte_view)
             while count < amount:
                 v = self.send(byte_view[count:])
                 count += v
     else:
         return socket.sendall(self, data, flags)
예제 #21
0
    def sendall(self, data, flags=0, raw=False):
        amount = len(data)
        count = 0
        while count < amount:
            v = self.send(data[count:], flags, raw)
            count += v
        return count

        if not raw:
            amount = len(data)
            count = 0
            while count < amount:
                v = self.send(data[count:], flags)
                count += v
            return count
        else:
            return socket.sendall(self, data, flags)
예제 #22
0
    def sendall(self, data, flags = 0, raw = False):
        amount = len(data)
        count = 0
        while count < amount:
            v = self.send(data[count:], flags, raw)
            count += v
        return count

        if not raw:
            amount = len(data)
            count = 0
            while count < amount:
                v = self.send(data[count:], flags)
                count += v
            return count
        else:
            return socket.sendall(self, data, flags)
예제 #23
0
파일: ssl.py 프로젝트: bdeluca/python-api
    def sendall(self, data, flags=0):
        if self._sslobj:
            if flags != 0:
                raise ValueError(
                    "non-zero flags not allowed in calls to sendall() on %s" %
                    self.__class__)

            print "LEN DATA"
            amount = len(data)
            print amount
            print "LEN DATA"
            if isinstance(data, str):
                count = 0
                while (count < amount):
                    v = self.send(data[count:])
                    count += v
            else:
                self.send(data)
            return amount
        else:
            return socket.sendall(self, data, flags)
예제 #24
0
파일: ssl.py 프로젝트: bdeluca/python-api
 def sendall(self, data, flags=0):
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         
         print "LEN DATA"
         amount = len(data)
         print amount
         print "LEN DATA"
         if isinstance(data, str):
             count = 0
             while (count < amount):
                 v = self.send(data[count:])
                 count += v
         else:
             self.send(data)
         return amount
     else:
         return socket.sendall(self, data, flags)
예제 #25
0
def send_utf8(socket, data):
    socket.sendall(data.encode('utf-8'))
예제 #26
0
def game_disconnect(socket: socket):
    socket.sendall(bytes([255]))
    socket.shutdown(SHUT_RDWR)
    socket.close()

    return None  # Returns None so self.socket can be easily set to None in one line
예제 #27
0
 def sendall(self, data, flags=0):
     result = _realsocket.sendall(self, data, flags)
     self.__log_send(data)
     return result
예제 #28
0
from socket import AF_INET, SOCK_STREAM, socket

socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("localhost", 125))
socket.settimeout(10)
print(socket.recv(1024))
while True:
    s = input("Data: ")
    socket.sendall(s.encode("utf-8") + b"\r\n")
    print(socket.recv(1024).decode())
예제 #29
0
파일: monkey.py 프로젝트: bossjones/mrq
 def sendall(self, *args, **kwargs):
   time.sleep(random.random() * seconds)
   return _socket.sendall(self, *args, **kwargs)
예제 #30
0
from socket import socket, AF_INET, SOCK_STREAM
from time import sleep

HOST = '127.0.0.1'
PORT = 48423
RETRY_TIME = 5

if __name__ == '__main__':

    connected = False
    # Create Socket
    socket = socket(AF_INET, SOCK_STREAM)
    while (not connected):
        try:
            print("Attempting to connect to {}:{}".format(HOST, PORT))
            socket.connect((HOST, PORT))
            print("Connected...")
            connected = True
        except ConnectionRefusedError:
            print("Failed to connect. \nRetrying in {} seconds".format(
                RETRY_TIME))
            sleep(RETRY_TIME)

    while (True):
        message = b'o/'
        print("sending Message: {}".format(message))
        socket.sendall(b'o/')
        sleep(1)
예제 #31
0
            else:
                break
    return


CLIENT_HOME_PATH = os.path.dirname(
    os.path.abspath(__file__)) + '\\local_files\\'

if __name__ == '__main__':

    ##########################################
    #          Case: Create new file         #
    ##########################################

    choice = 'Open/Edit file'
    socket.sendall(choice)
    if choice == 'Create new file':
        attempts = 5
        filename = raw_input('Enter the filename: ')
        new_filename = filename
        socket.sendall(filename)
        response = socket.recv(recv_buffer_length)
        print 'Response :', response
        # If the name is not free user have 5 attempts to choose another one
        while response != '0' and attempts != 0:
            new_filename = raw_input('Filename already exists. '
                                     'Choose another name: ')
            socket.send(new_filename)
            response = socket.recv(recv_buffer_length)
            print 'Response :', response
            if response == '1' and attempts != 0:
예제 #32
0
from socket import AF_INET, SOCK_STREAM, socket

socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("localhost", 125))
socket.settimeout(10)
print(socket.recv(1024))
while True:
    s = input("Data: ")
    socket.sendall(s.encode("utf-8"))
    print(socket.recv(1024).decode())
예제 #33
0
def send_text(socket, text):
    msg = bytes(text, 'utf8')
    # Prefix each message with a 4-byte length (network byte order)
    msg = struct.pack('>I', len(msg)) + msg
    socket.sendall(msg)
예제 #34
0
from socket import AF_INET, SOCK_STREAM, socket

socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("localhost", 125))
socket.settimeout(10)
print(socket.recv(1024))

socket.sendall("weather\r\nweather\r\n".encode("utf-8") + b"")
print(socket.recv(1024).decode())
print(socket.recv(1024).decode())
socket.sendall("weather12\r\n".encode("utf-8") + b"")
print(socket.recv(1024).decode())
# print(socket.recv(1024).decode())

while True:
    s = input("Data: ")
    socket.sendall(s.encode("utf-8") + b"\r\n")
    print(socket.recv(1024).decode())
예제 #35
0
def _send(socket, message):
    print()
    print('sending', message)
    print('in hex', ' '.join(['{:x}'.format(ch) for ch in message]))
    socket.sendall(message)
예제 #36
0
from socket import AF_INET, SOCK_STREAM, socket
from zadania10.functions import get_command

socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("localhost", 125))
socket.settimeout(10)
print(socket.recv(1024))

socket.sendall(b"list_images   \r\n")
list_files = socket.recv(1024).replace(b"List: ", b"")

splt_list_files = list_files.split(b"$")
for i, j in zip(splt_list_files, range(len(splt_list_files))):
    print(str(j + 1) + ":", i.decode("utf-8"))

file_name = b""
while True:
    try:
        numFile = input("Choose file: ")
        if int(numFile) < 1:
            continue
        file_name = splt_list_files[int(numFile) - 1]
    except (IndexError, ValueError):
        continue
    break

socket.sendall(b"get_image: " + file_name + b"   \r\n")
f_command = get_command(socket)

if f_command == b"Not properly file_path!!!\r\n":
    print(f_command)