示例#1
0
    def open(self):
        """Initializes sonar connection and sets default properties.

        Raises:
            SonarNotFound: Sonar port could not be opened.
        """
        if not self.conn:
            try:
                self.conn = Socket(self.port)
            except OSError as e:
                raise exceptions.SonarNotFound(self.port, e)

        # Update properties.
        rospy.loginfo("Initializing sonar on %s", self.port)
        self.initialized = True

        # Reboot to make sure the sonar is clean.
        self.send(Message.REBOOT)
        self.update()

        # Set default properties.
        self.set(force=True)

        # Wait for settings to go through.
        while not self.has_cfg or self.no_params or not self.motor_on or not self.centred:
            rospy.loginfo(
                "Waiting for configuration: (HAS CFG: %s, NO PARAMS: %s)",
                self.has_cfg, self.no_params
            )
            self.update()

        rospy.loginfo("Sonar is ready for use")
示例#2
0
def main():

    sys.stdout.flush()
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', '-p', default=2080, type=int,
                        help='Port to use')
    args = parser.parse_args()
    print(args.port)


    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:

        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # does not work in python3 with -p
        server_socket.bind(('0.0.0.0', args.port))

        server_socket.listen(0)
        print("server ready")

        while True:

            with server_socket.accept()[0] as connection_socket:

                data_str = connection_socket.recv(1024).decode('ascii')
                print(data_str)

                connection_socket.send(http_handle(data_str).encode('ascii'))
                connection_socket.close()

    return 0
示例#3
0
def run_server(server_port):
    """Run the UDP pinger server
    """

    # Create the server socket (to handle UDP requests using ipv4), make sure
    # it is always closed by using with statement.
    with Socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:

        # The socket stays connected even after this script ends. So in order
        # to allow the immediate reuse of the socket (so that we can kill and
        # re-run the server while debugging) we set the following option. This
        # is potentially dangerous in real code: in rare cases you may get junk
        # data arriving at the socket.
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Set the server port
        server_socket.bind(('', server_port))

        # Start accepting ping requests
        print("Ping server ready on port", server_port)
        while True:
            # Receive message and send one back
            _, client_address = server_socket.recvfrom(1024)
            server_socket.sendto("".encode(), client_address)

    return 0
示例#4
0
def run(host: str, serv: int, username: str, password: str,
        args: List[str]) -> None:
    try:
        opts, args = getopt(args, 's:e:')
    except GetoptError:
        usage()
    if args:
        usage()

    start = EPOCH
    end = datetime.now()
    for opt, arg in opts:
        if opt == '-s':
            from dateparser import parse  # type: ignore
            start = parse(arg)
            if start is None:
                usage()
        if opt == '-e':
            from dateparser import parse  # type: ignore
            end = parse(arg)
            if end is None:
                usage()

    conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
    conn.connect((host, serv), username, password)
    try:
        for entry in conn.log(start=start, end=end):
            print('{:>8} {} {:>12} {}'.format(entry.number,
                                              entry.time.isoformat(),
                                              entry.type.name.lower(),
                                              entry.data))
    finally:
        conn.logout()
def run_client(server_address, server_port):
    # Measure RTT for 10 times
    for i in range(0, 10):
        # Create UDP socket
        with Socket(socket.AF_INET, socket.SOCK_DGRAM) as client_socket:

            # set timeout to 1s
            client_socket.settimeout(1)

            # Specify the addr and port to connect to
            client_socket.connect((server_address, server_port))

            print('#%d ' % i, end='')

            # Measure RTT
            start = time.time_ns()

            # Send UDP ping packet
            client_socket.send(b'ping!')

            try:
                recv_ = client_socket.recv(4096)
            except socket.timeout:
                recv_ = None

            end = time.time_ns()
            elapsed = end - start

            # If pong packet is received normally
            if recv_ == b'pong!':
                print('RTT: %.2fms' % (elapsed / (10 ** 6)))
            else:
                print('Request Timeout')
示例#6
0
    def open(self):
        """Initializes sonar connection and sets default properties.

        Raises:
            SonarNotFound: Sonar port could not be opened.
        """
        if not self.conn:
            try:
                self.conn = Socket(self.port)
            except OSError as e:
                raise exceptions.SonarNotFound(self.port, e)

        # Update properties.
        rospy.loginfo("Initializing sonar on %s", self.port)
        self.initialized = True

        # Reboot to make sure the sonar is clean.
        self.send(Message.REBOOT)
        self.update()

        # Set default properties.
        self.set(force=True)

        # Wait for settings to go through.
        while not self.has_cfg or self.no_params:
            rospy.loginfo(
                "Waiting for configuration: (HAS CFG: %s, NO PARAMS: %s)",
                self.has_cfg, self.no_params
            )
            self.update()

        rospy.loginfo("Sonar is ready for use")
示例#7
0
def main():

    # 相应网页的内容

    # Create the server socket (to handle tcp requests using ipv4), make sure
    # it is always closed by using with statement.
    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:

        # The socket stays connected even after this script ends. So in order
        # to allow the immediate reuse of the socket (so that we can kill and
        # re-run the server while debugging) we set the following option. This
        # is potentially dangerous in real code: in rare cases you may get junk
        # data arriving at the socket.
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #设置连接及端口号
        server_socket.bind(('', args.port))
        server_socket.listen(10)

        print("服务器就绪,等待连接")

        while 1:
            #得到响应信息
            conn, addr = server_socket.accept()
            task = threading.Thread(target=soc, args=(conn, addr))
            task.start()

        server_socket.close()

    return 0
示例#8
0
def run(host: str,  # pylint: disable=too-many-branches,too-many-locals
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	if args:
		usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)

	info = conn.systeminfo()
	line = [info.chassis, info.board, info.serial]
	for attr in ('hardware', 'eeprom', 'software', 'build', 'videoin',
	             'videoout', 'commin', 'commout', 'triggerin',
	             'triggerout', 'audioin', 'views'):
		value = getattr(info, attr)
		if value:
			line.append('{} {}'.format(attr, value))
	print(' '.join(line))  # system line

	for disk in conn.storageinfo():
		print('disk {}:'.format(disk.number))  # disk group
		for i, part in zip(range(disk.parts), disk.partinfo):
			line = ['  part {}'.format(i)]
			if part.current:
				line.append('current')
			line.append('size {}M free {}M'
			            .format(part.size, part.free))
			for attr in ('viewedstart', 'viewedend',
			             'unviewedstart', 'unviewedend'):
				date = getattr(part, attr)
				line.append('{} {}'
				            .format(attr, date.isoformat()))
			print(' '.join(line))  # partition line

	actv = conn.activityinfo()
	line = []
	for i, chan in zip(range(info.videoin), actv.channels):
		print('channel {} bitrate {}K/s'.format(i, chan.bitrate) +
		      (' recording' if chan.recording else ''))

	line = []
	line.append(conn.time().isoformat())
	minutes = info.uptime
	hours, minutes = divmod(minutes, 60)
	days, hours = divmod(hours, 24)
	if days:
		line.append("up P{}dT{:02}h{:02}m".format(days, hours, minutes))
	else:
		line.append("up PT{}h{:02}m".format(hours, minutes))
	line.append('triggers')
	for attr in ('in_', 'out', 'obscure', 'disconnect', 'motion'):
		value = getattr(actv.triggers, attr)
		if value:
			line.append('{} {}'.format(attr.rstrip('_'), value))
	if len(line) <= 3:
		line.append('none')
	print(' '.join(line))  # status line
def start_client():
    # Client (Player) Setup

    # import needed libraries
    from socket import socket as Socket
    from socket import AF_INET, SOCK_STREAM

    HOSTNAME = 'localhost'  # on same host
    PORTNUMBER = 11267      # same port number
    BUFFER = 80             # size of the buffer

    SERVER = (HOSTNAME, PORTNUMBER)
    PLAYER = Socket(AF_INET, SOCK_STREAM)
    PLAYER.connect(SERVER)

    print(f'PLAYER >> Connected to SERVER over port {PORTNUMBER}.')
    while True:
        GUESS = input('PLAYER >> Guess the password: '******'SERVER >>', ANSWER)
        
        if ANSWER == 'You chose wisely.':
            break

    PLAYER.close()
def start_client():
    # Client Setup

    # import needed libraries
    from socket import socket as Socket
    from socket import AF_INET, SOCK_STREAM

    HOSTNAME = 'localhost'  # on same host
    PORTNUMBER = 12345  # same port number as server
    BUFFER = 1024  # size of the buffer

    SERVER = (HOSTNAME, PORTNUMBER)  # create tuple of server address
    CLIENT2 = Socket(AF_INET, SOCK_STREAM)  # create client socket
    CLIENT2.connect(SERVER)  # connect client socket to server socket

    print(f'CLIENT2 >> Connected to SERVER over port {PORTNUMBER}.'
          )  # print verification string

    # loop until 'QUIT' is sent and received
    while True:
        MESSAGE2 = input(
            'CLIENT2 >> Enter data you want to send or "QUIT" to exit-> '
        )  # message to send to server
        CLIENT2.send(MESSAGE2.encode())  # send the encoded message to server
        REPLY2 = CLIENT2.recv(BUFFER).decode()  # receive the servers reply

        print('SERVER >>', REPLY2)  # print out the reply from server

        # break out of loop if QUIT is received
        if REPLY2 == 'QUIT':
            break

    print("CLIENT2 >> Closing Socket, GOODBYE."
          )  # print out break out of loop verification string
    CLIENT2.close()  # close the socket
示例#11
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):

    host = str(config.get(CONF_HOST))
    port = int(config.get(CONF_PORT))
    username = str(config.get(CONF_USERNAME))
    password = str(config.get(CONF_PASSWORD))
    if (password is None):
        password = ''
    _LOGGER.info("Connecting to %s:%i using %s:%s" %
                 (host, port, username, password))

    from dvrip.io import DVRIPClient

    client = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
    client.connect((host, port), username, password)
    info = client.systeminfo()
    _LOGGER.info("Connected to %s. It has %i video-in. Will add %i cameras" %
                 (info.board, info.videoin, info.videoin))
    cameras = []
    for camera in range(int(info.videoin)):
        _LOGGER.info("Detected video-in nr %i" % (camera))
        cameras.append(XMEye_Camera(hass, client, camera, (host, port)))

    async_add_entities(cameras)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--port',
                        '-p',
                        default=2000,
                        type=int,
                        help='port to use')
    args = parser.parse_args()
    server_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('', args.port))
    server_socket.listen(1)
    print "server running"
    while True:
        connection_socket = server_socket.accept()[0]
        request = connection_socket.recv(1024)
        reply = http_handler(request)
        connection_socket.send("HTTP/1.1 200 OK\n")
        connection_socket.send("\n")

        connection_socket.send(reply)
        connection_socket.close()

        print "received request"
        print "reply sent"

    return 0
示例#13
0
    def __init__(
            self,
            email: Optional[str] = None,
            model_name: Optional[str] = None,
            callback: Optional[Callable] = None,
            job_config: JobConfig = JobConfig(),
            address: Tuple[str, int] = ("sybl.tech", 7000),
    ) -> None:

        self.email: Optional[str] = email
        self.model_name: Optional[str] = model_name

        self._access_token: Optional[str] = None
        self._model_id: Optional[str] = None
        if email and model_name:
            self._access_token, self._model_id = load_access_token(
                email, model_name)

        self._sock: Socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
        self._state: State = State.AUTHENTICATING
        self._address: Tuple[str, int] = address

        if callback:
            self.register_callback(callback)
        else:
            self.callback: Optional[Callable] = None

        self.config: JobConfig = job_config
        self.recv_job_config: Optional[Dict] = None

        self._message_stack: List[Dict] = []
示例#14
0
def main():

    sys.stdout.flush()
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', '-p', default=2080, type=int,
                        help='Port to use')
    args = parser.parse_args()
    print(args.port)

    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:

        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # does not work in python3 with -p
        server_socket.bind(('', args.port))

        server_socket.listen(0)


        print("server ready")

        while True:

            connection_socket, address = server_socket.accept()


            while (threading.activeCount() >= 20):
                continue

            Thread(target = http_handle, args = (connection_socket, address) ).start()

    return 0
示例#15
0
def redirector():
    """
    Redirects all incoming traffic through the proxy.
    """
    PROXY_HOST = environ.get("PROXY_HOST")
    PROXY_PORT = environ.get("PROXY_PORT", 1080)

    setdefaultproxy(PROXY_TYPE_SOCKS5, PROXY_HOST, PROXY_PORT)

    server = Socket(AF_INET, SOCK_STREAM)
    server.bind(("127.0.0.1", 42000))
    server.listen(5)

    while True:
        client_socket, (src_host, src_port) = server.accept()
        (dst_host, dst_port) = get_original_destination(client_socket)

        logger.info(
            f"Intercepted connection from {src_host}:{src_port} to {dst_host}:{dst_port}"
        )

        proxy_socket = SocksSocket()
        proxy_socket.connect((dst_host, dst_port))

        bidirectional_copy(client_socket, proxy_socket)
示例#16
0
def main():

    #  Argumentos da linha de comando. Use a porta 8080 por padrão: amplamente usado para proxys
    # e > 1024, então não precisamos de sudo para rodar.
    parser = argparse.ArgumentParser()
    parser.add_argument('--porta', '-p', default=8080, type=int, help='porta para usar')
    args = parser.parse_args()

    # Crie o sockete do servidor (para manipular solicitações tcp usando ipv4), certifique-se
    # é sempre fechado usando a instrução    
    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:

        # O socket permanece conectado mesmo depois que este script terminar
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        server_socket.bind(('', args.port))
        server_socket.listen(1)
        # sem multithread ainda, precisaria configurar atualizações atômicas para dict.
        # Criar um dicionario vazio para páginas em cache
        cache_dict = {}

        print("servidor proxy pronto")

        while True:
            # Aceite a conexão TCP do cliente
            with server_socket.accept()[0] as connection_socket:

    return 0
示例#17
0
文件: urb.py 项目: paul-freeman/urb
    def update(self):
        """Get data from the oscilloscope.

        :returns: the trace data
        :rtype: numpy.array dtype='(*number_channels*,*number_samples*)int16'
        """
        self._scope = Socket(AF_INET, SOCK_STREAM)
        self._scope.settimeout(5.0)
        self._scope.connect((self._ip_address, 4000))
        #self._activate_acquisition()
        field = '{}-trace'.format(self.__class__.__name__)
        type_ = '({:d},{:d})int16'.format(len(self._channels),
                                          self._record_length)
        data = np.zeros((1, ), dtype=[(field, type_)])
        print('transfering waveform... ', end='')
        sys.stdout.flush()
        for channel, active in enumerate(self._channels):
            if not active:
                continue
            self._request_curve(channel + 1)
            trace = self._receive_curve()
            data[field][0][channel] = trace
        self._scope.close()
        print('done')
        return data.copy()
def main():
    # Command line arguments. Use a port > 1024 by default so that we can run
    # without sudo, for use as a real server you need to use port 80.
    parser = argparse.ArgumentParser()
    parser.add_argument('--port',
                        '-p',
                        default=2080,
                        type=int,
                        help='Port to use')
    args = parser.parse_args()

    # Create the server socket (to handle tcp requests using ipv4), make sure
    # it is always closed by using with statement.
    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        # The socket stays connected even after this script ends. So in order
        # to allow the immediate reuse of the socket (so that we can kill and
        # re-run the server while debugging) we set the following option. This
        # is potentially dangerous in real code: in rare cases you may get junk
        # data arriving at the socket.

        # Set socket options
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Bind socket to port
        print("Using the port: ", args.port)
        server_socket.bind(('', args.port))

        # Have socket listen
        server_socket.listen(0)

        print("server ready")

        while True:
            # Use the server socket as the connection socket and accept incoming requests
            # This is like file IO and you need to open the server socket as the connection socket
            with server_socket.accept()[0] as connection_socket:
                # Save the request received from the connection and decode as ascii
                data_str = connection_socket.recv(1024).decode('ascii')
                request = data_str
                reply = http_handle(request)

                # Generate a reply by sending the request received to http_handle()
                # See function http_handle()

                # Use the connection socket to send the reply encoded as bytestream
                reply = reply.rstrip()
                reply_encoded = reply.encode('ascii')

                print("\n\nReceived request")
                print("======================")
                print(request.rstrip())
                print("======================")
                print("\n\nReplied with")
                print("======================")
                print(reply)
                connection_socket.send(reply_encoded)
                print("======================")
def main():

    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:

        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Bind the socket to address
        # (arg1, arg2) HOST, PORT
        server_socket.bind(('', 2080))

        # Enable a server to accept connections
        # (arg) number of unaccepted connections
        server_socket.listen(1)
        print("Server On")
        while True:
            # Get the clientSocket and end it when it is done
            with server_socket.accept()[0] as clientSocket:
                # Keeps the connection awake while the client is on
                print("\nNew Client")
                while True:
                    # HTTP requests
                    request = clientSocket.recv(1024)
                    request = request.decode()
                    if not request: break

                    print("\nRequest", request)

                    (method, fileName, contentSize) = httpHandle(request)

                    if (method == "GET"):
                        # Check if file exists
                        exists = os.path.isfile(fileName)
                        if not exists:
                            method = "404"

                    if (method == 'GET'):
                        responseHeader = \
                        "HTTP/1.1 200 OK\n"+\
                        "Content-Length: " + str(fileSize(fileName)) +'\n'
                        sendHeader(responseHeader, clientSocket)
                        clientSocket.recv(1024)
                        sendFile(fileName, clientSocket)
                        print("File ", fileName, " sent to client!")
                    elif (method == 'SEND'):
                        responseHeader = "HTTP/1.1 200 OK\n"
                        clientSocket.send(responseHeader.encode())
                        receiveFile(fileName, int(contentSize), clientSocket)
                        print("File ", fileName, " saved in folder files!")
                    else:
                        responseHeader = "HTTP/1.1 404 Not Found\n"
                        contentLength = "Content-Length: 0\n"
                        clientSocket.sendall(responseHeader.encode())
                        clientSocket.sendall(contentLength.encode())
                clientSocket.close()
            print("Client has left")

    return 0
示例#20
0
文件: urb.py 项目: paul-freeman/urb
 def _mode(self, wave):
     with Socket(AF_INET, SOCK_STREAM) as socket:
         socket.settimeout(5)
         socket.connect((self.urb.ip_address, self.urb.port))
         socket.send(
             bytes("Wave {} {}\r\n".format(self.stacknum, wave),
                   encoding='ascii'))
         query = literal_eval(recv_end(socket))
         socket.shutdown(SHUT_RDWR)
     self.mode = query['mode']
示例#21
0
def main():
    print 'Starting...'
    socket = Socket(AF_INET, SOCK_DGRAM)
    packetID = 1
    while packetID:
        socket.sendto('{}, {:.9f}'.format(packetID, time()),
                      ('192.168.1.2', 41724))
        print 'Packet with ID {} sent.'.format(packetID)
        sleep(1)
        packetID += 1
示例#22
0
    def _tryInitSocket() -> None:
        """
    Initializes the underlying ping socket,
    if not already initialized.
    """
        if not Pinger._socket:
            Pinger._socket = Socket(AF_INET, SOCK_RAW,
                                    socket.getprotobyname('icmp'))

            Pinger._socket.setblocking(False)
示例#23
0
 def remote(cls, port, environment, max_episode_timesteps=None, **kwargs):
     socket = Socket()
     socket.bind(('', port))
     socket.listen(1)
     connection, address = socket.accept()
     socket.close()
     super().remote(connection=connection,
                    environment=environment,
                    max_episode_timesteps=max_episode_timesteps,
                    **kwargs)
def start_server():
    # import needed libraries
    from random import randint
    from socket import socket as Socket
    from socket import AF_INET, SOCK_STREAM

    # Server Setup
    HOSTNAME = ''       # blank so any address can be used
    PORTNUMBER = 12345  # number for the port
    BUFFER = 1024       # size of the buffer
    SERVER_ADDRESS = (HOSTNAME, PORTNUMBER)         # make the server address a tuple
    SERVER = Socket(AF_INET, SOCK_STREAM)           # create the server socket
    print("SERVER >> Socket successfully created")  # print out socket successfully created
    SERVER.bind(SERVER_ADDRESS)                     # bind the socket to the address
    print("SERVER >> Socket binded to 12345")       # print out socket successfully binded
    SERVER.listen(2)                                # start listening on the socket for connections
    print("SERVER >> Socket is listening")          # print out verification that socket is listening

    # receive client connections
    CLIENT1, CLIENT1_ADDRESS = SERVER.accept()                # receive the connection from client1 and save the socket and client address
    CLIENT2, CLIENT2_ADDRESS = SERVER.accept()                # receive the connection from client2 and save the socket and client address
    print('SERVER >> Got connection from ', CLIENT1_ADDRESS)  # print connection1 verification string
    print('SERVER >> Got connection from ', CLIENT2_ADDRESS)  # print connection2 verification string
    
    # loop until message received is "QUIT"
    while True:
        MESSAGE1 = CLIENT1.recv(BUFFER).decode()  # receive message1 from client1 and decode it
        REPLY1 = ""                               # instantiate reply1 as an empty string
        MESSAGE2 = CLIENT2.recv(BUFFER).decode()  # receive message2 from client2 and decode it
        REPLY2 = ""                               # instantiate reply2 as an empty string
        
        # if receive "QUIT" from client1, send "QUIT back to both clients and break out of loop to close the socket"
        if MESSAGE1 == "QUIT":
            REPLY1 = "QUIT"
            CLIENT1.send(REPLY1.encode())
            CLIENT2.send(REPLY1.encode())
            break
        # if receive "QUIT" from client2, send "QUIT back to both clients and break out of loop to close the socket"
        elif MESSAGE2 == "QUIT":
            REPLY2 = "QUIT"
            CLIENT2.send(REPLY2.encode())
            CLIENT1.send(REPLY2.encode())
            break
        # otherwise, reverse the messages received and send them back to clients
        else:
            length1 = len(MESSAGE1)             # get MESSAGE1 length
            length2 = len(MESSAGE2)             # get MESSAGE2 length
            REPLY1 = MESSAGE1[length1::-1]      # make REPLY1 the MESSAGE1 reversed
            REPLY2 = MESSAGE2[length2::-1]      # make REPLY2 the MESSAGE2 reversed
            CLIENT1.send(REPLY1.encode())       # send encoded REPLY1 to CLIENT1
            CLIENT2.send(REPLY2.encode())       # send encoded REPLY2 to CLIENT2
    
    print('SERVER >> Closing Socket, GOODBYE.') # print out break out of loop verification string
    SERVER.close()  # close out the socket
示例#25
0
def _open_new_socket(server_hostname: str, server_port: int,
                     logger: Logger) -> Union[ssl.SSLSocket, Socket]:
    if server_port != 443:
        # only for library testing
        logger.info(
            f"Using non-ssl socket to connect ({server_hostname}:{server_port})"
        )
        sock = Socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3)
        return sock

    sock = Socket(type=ssl.SOCK_STREAM)
    sock = ssl.SSLContext(ssl.PROTOCOL_SSLv23).wrap_socket(
        sock,
        do_handshake_on_connect=True,
        suppress_ragged_eofs=True,
        server_hostname=server_hostname,
    )
    sock.settimeout(5)
    return sock
示例#26
0
文件: time.py 项目: wyatt303/dvrip
def run(host: str, serv: int, username: str, password: str,
        args: List[str]) -> None:
    if args:
        from dateparser import parse  # type: ignore
        time = parse(args[0])
        if len(args) > 2 or time is None or time.tzinfo is not None:
            usage()

    conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
    conn.connect((host, serv), username, password)
    print((conn.time(time) if args else conn.time()).isoformat())
示例#27
0
def main():
    # create
    with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        # connect
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # connect to localhost port 2080
        server_socket.bind(('', 2080))
        server_socket.listen(1)

        print("server ready")

        while True:
            # connection, client_address = server_socket.accept()
            with server_socket.accept()[0] as connection_socket:
                # receive --command and --content
                message = connection_socket.recv(1024).decode()
                print("I receive " + message)

                command = message.split('-')[0]

                if command == "GET" or command == "GETPROG":
                    idx = len(command) + 1
                    request = message[idx:]
                elif command == "POST":
                    toFile = message.split('-')[1]
                    idx = len(command) + len(toFile) + 2
                    request = message[idx:]
                    print("File to save: " + toFile)

                print("Command: " + command)
                print("Request: " + request)

                if command == "GET" or command == "GETPROG":
                    reply = http_handle(
                        request)  # read archive and returns its content
                    connection_socket.send(reply)  # send message
                    print("Success")
                elif command == "POST":
                    path = "filesPOST/" + toFile

                    with open(path,
                              "wb") as f:  # save contents in output files
                        f.write(request.encode())

                        while request:
                            request = connection_socket.recv(1024)
                            f.write(request)

                    print("Success")
                else:
                    print("Command not supported")

    return 0
def connectToServer(url, request, domain):

    hostIP = socket.gethostbyname(domain)
    with Socket(socket.AF_INET, socket.SOCK_STREAM) as outside_socket:
        outside_socket.connect((hostIP, 80))
        outside_socket.sendall(bytearray(request, 'utf-8'))

        response = outside_socket.recv(1024)

        outside_socket.close()
        return response
示例#29
0
    def open(self):
        """
        Initializes sonar connection and sets default properties.

        :raises: SonarNotFound: Sonar port could not be opened.

        """
        print 'open'
        if not self.conn:
            try:
                self.conn = Socket(self.port)
            except OSError as e:
                raise exceptions.SonarNotFound(self.port, e)

        # Update properties.
        rospy.loginfo("Initializing sonar on %s", self.port)
        self.initialized = True

        # Reboot to make sure the sonar is clean.
        self.send(Message.REBOOT)
        self.update()
        self.send(Message.REBOOT)
        #rospy.loginfo('Sending Version Data request...')
        #self.send(Message.SEND_VERSION)
        #self.get(Message.VERSION_DATA, 1)
        #rospy.loginfo('Version Data message received')

        #self.send(Message.SEND_BB_USER)
        #self.get(Message.BB_USER_DATA)

        # Set default properties.
        self.set(force=True)

        # Wait for settings to go through.
        while not self.has_cfg or self.no_params:
            rospy.loginfo(
                "Waiting for configuration: (HAS CFG: %s, NO PARAMS: %s)",
                self.has_cfg, self.no_params)
            self.update()

        rospy.loginfo("Sonar is ready for use")
示例#30
0
    def start( self ):

        Thread( target = self.readStdIn ).start( )
        
        socket = Socket( AF_INET, SOCK_STREAM )
        try:
            socket.connect( self.remotePeer.addr )
            socket.send( 'CLIENT' )
            self.remotePeer.onConnect( socket )
        except SocketError:
            print 'failed to connect to server'
            os._exit( 1 )
示例#31
0
def main():
    HOSTNAME = 'localhost'  # on same host
    PORTNUMBER = 11267  # same port number
    BUFFER = 80  # size of the buffer

    DEALER = (HOSTNAME, PORTNUMBER)
    PLAYER = Socket(AF_INET, SOCK_STREAM)
    PLAYER.connect(DEALER)

    playGame(PLAYER, BUFFER)

    PLAYER.close()
示例#32
0
class RegistryClient(object, IRegistryClient):
    def __init__(self, update_period=10, refresh_callback=None, server_uri=None):
        if server_uri:
            self.server_uri = server_uri
        else:
            self.server_uri = SERVER_URI

        self.__refresh_callback = refresh_callback
        self.__update_period = update_period
        self.__socket = Socket(self.server_uri)
        self.__registry = Registry()
        self.refresh()
        self.__update_thread = UpdateThread(self, update_period)
        self.__update_thread.daemon = True
        self.__update_thread.start()

    def get(self, key):
        return self.__registry.get(key)

    def set(self, key, value):
        return self.__registry.set(key, value)

    def remove(self, key):
        return self.__registry.remove(key)

    def refresh(self):
        current_version = self.__socket.send('get_version')
        if self.__registry.get_version() != current_version:
            self._load()
            if self.__refresh_callback:
                self.__refresh_callback(self)

    def _load(self):
        try:
            (version, values) = self.__socket.send('get_values')
            self.__registry.set_values(values, version)
        except Exception, err:
            print "Ops:", err
            pass
示例#33
0
    def __init__(self, update_period=10, refresh_callback=None, server_uri=None):
        if server_uri:
            self.server_uri = server_uri
        else:
            self.server_uri = SERVER_URI

        self.__refresh_callback = refresh_callback
        self.__update_period = update_period
        self.__socket = Socket(self.server_uri)
        self.__registry = Registry()
        self.refresh()
        self.__update_thread = UpdateThread(self, update_period)
        self.__update_thread.daemon = True
        self.__update_thread.start()
示例#34
0
class TritechMicron(object):

    """Tritech Micron sonar.

    In order for attribute changes to immediately be reflected on the device,
    use the set() method with the appropriate keyword.

    For example, to setup a 20 m sector scan:

        with TritechMicron() as sonar:
            sonar.set(continuous=False, range=20)

    All angles are in radians and headings are relative to the blue LED. So, if
    the sonar were not inverted, 0 radians would be facing forward.

    Attributes:
        ad_high: Amplitude in db to be mapped to max intensity (0-80 db).
        ad_low: Amplitude in dB to be mapped to 0 intensity (0-80 db).
        adc8on: True if 8-bit resolution ADC, otherwise 4-bit.
        centred: Whether the sonar motor is centred.
        clock: Sonar time of the day.
        conn: Serial connection.
        continuous: True if continuous scan, otherwise sector scan.
        gain: Initial gain percentage (0.00-1.00).
        has_cfg: Whether the sonar has acknowledged with mtBBUserData.
        heading: Current sonar heading in radians.
        initialized: Whether the sonar has been initialized with parameters.
        inverted: Whether the sonar is mounted upside down.
        left_limit: Left limit of sector scan in radians.
        mo_time: High speed limit of the motor in units of 10 microseconds.
        motoring: Whether the sonar motor is moving.
        motor_on: Whether device is powered and motor is primed.
        nbins: Number of bins per scan line.
        no_params: Whether the sonar needs parameters before it can scan.
        up_time: Sonar up time.
        port: Serial port.
        range: Scan range in meters.
        recentering: Whether the sonar is recentering its motor.
        right_limit: Right limit of sector scans in radians.
        scanning: Whether the sonar is scanning.
        scanright: Whether the sonar scanning direction is clockwise.
        speed: Speed of sound in medium.
        step: Mechanical resolution (Resolution enumeration).
    """

    def __init__(self, port="/dev/sonar", **kwargs):
        """Constructs Sonar object.

        Args:
            port: Serial port (default: /dev/sonar).
            kwargs: Key-word arguments to pass to set() on initialization.
        """
        # Parameter defaults.
        self.ad_high = 80.0
        self.ad_low = 0.00
        self.adc8on = True
        self.continuous = True
        self.gain = 0.50
        self.inverted = False
        self.left_limit = to_radians(2400)
        self.mo_time = 250
        self.nbins = 400
        self.range = 10.00
        self.right_limit = to_radians(4000)
        self.scanright = True
        self.speed = 1500.0
        self.step = Resolution.LOW

        # Override defaults with key-word arguments or ROS parameters.
        for key, value in self.__dict__.iteritems():
            if key in kwargs:
                self.__setattr__(key, value)
            else:
                param = "{}/{}".format(rospy.get_name(), key)
                if rospy.has_param(param):
                    self.__setattr__(key, rospy.get_param(param))

        # Connection properties.
        self.port = port
        self.conn = None
        self.initialized = False

        # Head info.
        self.centred = False
        self.has_cfg = False
        self.heading = None
        self.motor_on = False
        self.motoring = False
        self.no_params = True
        self.up_time = datetime.timedelta(0)
        self.recentering = False
        self.scanning = False

        # Additional properties.
        self.clock = datetime.timedelta(0)
        self._time_offset = datetime.timedelta(0)
        self.preempted = False

    def __enter__(self):
        """Initializes sonar for first use.

        Raises:
            SonarNotFound: Sonar port could not be opened.
        """
        self.open()
        return self

    def __exit__(self, type, value, traceback):
        """Cleans up."""
        self.close()

    def open(self):
        """Initializes sonar connection and sets default properties.

        Raises:
            SonarNotFound: Sonar port could not be opened.
        """
        if not self.conn:
            try:
                self.conn = Socket(self.port)
            except OSError as e:
                raise exceptions.SonarNotFound(self.port, e)

        # Update properties.
        rospy.loginfo("Initializing sonar on %s", self.port)
        self.initialized = True

        # Reboot to make sure the sonar is clean.
        self.send(Message.REBOOT)
        self.update()

        # Set default properties.
        self.set(force=True)

        # Wait for settings to go through.
        while not self.has_cfg or self.no_params:
            rospy.loginfo(
                "Waiting for configuration: (HAS CFG: %s, NO PARAMS: %s)",
                self.has_cfg, self.no_params
            )
            self.update()

        rospy.loginfo("Sonar is ready for use")

    def close(self):
        """Closes sonar connection."""
        # Reboot first to clear sonar of all parameters.
        self.send(Message.REBOOT)
        self.conn.close()
        self.initialized = False
        rospy.loginfo("Closed sonar socket")

    def get(self, message=None, wait=2):
        """Sends command and returns reply.

        Args:
            message: Message to expect (default: first to come in).
            wait: Seconds to wait until received if a specific message is
                required (default: 2).

        Returns:
            Reply.

        Raises:
            SonarNotInitialized: Attempt reading serial without opening port.
            TimeoutError: Process timed out while waiting for specific message.
        """
        # Verify sonar is initialized.
        if not self.initialized:
            raise exceptions.SonarNotInitialized()

        expected_name = None
        if message:
            expected_name = Message.to_string(message)
            rospy.logdebug("Waiting for %s message", expected_name)

        # Determine end time.
        end = datetime.datetime.now() + datetime.timedelta(seconds=wait)

        # Wait until received if a specific message ID is requested, otherwise
        # wait forever.
        while message is None or datetime.datetime.now() < end:
            try:
                reply = self.conn.get_reply()

                # Update state if mtAlive.
                if reply.id == Message.ALIVE:
                    self.__update_state(reply)

                # If first was asked, respond immediately.
                if message is None:
                    return reply

                # Otherwise, verify reply ID.
                if reply.id == message:
                    rospy.logdebug("Found %s message", expected_name)
                    return reply
                elif reply.id != Message.ALIVE:
                    rospy.logwarn(
                        "Received unexpected %s message",
                        reply.name
                    )
            except exceptions.PacketCorrupted, serial.SerialException:
                # Keep trying.
                continue

        # Timeout.
        rospy.logerr("Timed out before receiving message: %s", expected_name)
        raise exceptions.TimeoutError()