示例#1
0
def close_sockets(receiver_sockets):
    """Close the sockets connection gracefully."""
    for socket in receiver_sockets:
        try:
            # We flush the buffer before closing connection if connection is TCP
            if socket.protocol == 1:
                socket.sock.settimeout(5)
                socket.receive()  # Flush buffer before closing connection
            socket.close()
        except OSError as e:
            if e.errno == 9:
                # Do not try to close the socket again if it was reused or closed already
                pass
示例#2
0
def command_record():
    try:
        with get_car_socket() as socket:
            socket.send("record")
            recv_string = socket.receive()
    except:
        pass
    return jsonify(result=recv_string)
示例#3
0
def command_go():
    recv_string = "error"
    try:
        with get_car_socket() as socket:
            socket.send("go")
            recv_string = socket.receive()
    except:
        pass
    return jsonify(result=recv_string)
示例#4
0
def get_car_scan():
#    recv_string = '{"vbat":3}'
    rv = ""
    try:
        since = request.args.get('since', '-1')
        with get_car_socket() as socket:
            socket.send("get_scan,"+str(since))
            rv = socket.receive()
    except:
        pass
    return Response(rv,mimetype='application/json')    
示例#5
0
def client_read(client):
    command, song = socket.receive()
    if(command == "list"):
        client.setCommand("list")
        client_write(client)
    elif(command == "play"):
        client.setCommand("play")
        client.setSong(song)
        client_write(client)
    elif(command == "stop")
        client.setCommand("stop")
        client_write(client)
    else:
        print("Bye!")
        exit(0)
示例#6
0
def run_example():
    print("Server (s) oder Client (c) ?")
    choice = input()
    
    if choice == "s":
        socket = connect_as_server()
    elif choice == "c":
        socket = connect_as_client()
    else:
        print("Unbekannte Funktion!")
        return
        
    socket.send("Hallo Welt!")
    print(socket.receive())
    socket.close()
示例#7
0
    def put(self, socket):

        wsprotocol = socket.protocol

        while not self.session.is_expired():
            try:
                messages = socket.receive() # blocking
            # geventwebsocket doesn't wrap these failure modes
            # into nice exceptions so we have to catch base Python
            # Exceptions. :(

            # Ignore invalid frames
            except ValueError:
                continue
            except TypeError:
                continue
            # Ignore empty frames
            except WebSocketError:
                continue
            # If the peer closes early then a fobj.read attribute
            # won't exist so ignore.
            except AttributeError:
                break
            #except socketerror:
                #break

            # Hybi = Closed
            # Hixie = None

            if messages is None:
                break

            try:
                messages = protocol.decode(messages)
            except InvalidJSON:
                # When user sends broken data - broken JSON for example, the
                # server must terminate the ws connection.
                break

            for msg in messages:
                self.conn.on_message(msg)

            self.session.incr_hits()

        # Session expires, so unlock
        socket.close()
        self.session.unlock()
        self.session.expire()
示例#8
0
    def put(self, socket):

        wsprotocol = socket.protocol

        while not self.session.is_expired():
            try:
                messages = socket.receive() # blocking
            # geventwebsocket doesn't wrap these failure modes
            # into nice exceptions so we have to catch base Python
            # Exceptions. :(

            # Ignore invalid frames
            except ValueError:
                continue
            except TypeError:
                continue
            # Ignore empty frames
            except WebSocketError:
                continue
            # If the peer closes early then a fobj.read attribute
            # won't exist so ignore.
            except AttributeError:
                break
            #except socketerror:
                #break

            # Hybi = Closed
            # Hixie = None

            if isinstance(messages, Closed) or messages is None:
                break

            try:
                messages = protocol.decode(messages)
            except InvalidJSON:
                # When user sends broken data - broken JSON for example, the
                # server must terminate the ws connection.
                break

            for msg in messages:
                self.conn.on_message(msg)

            self.session.incr_hits()

        # Session expires, so unlock
        socket.close()
        self.session.unlock()
        self.session.expire()
示例#9
0
    def put(self, socket):

        while not self.session.is_expired():
            # Just read atomic strings and do what the connection
            # wants.

            message = socket.receive() # blocking

            if message is None:
                break

            self.conn.on_message([message])

            self.session.incr_hits()

        socket.close()
示例#10
0
    def put(self, socket):

        while not self.session.is_expired():
            # Just read atomic strings and do what the connection
            # wants.

            message = socket.receive() # blocking

            if isinstance(message, Closed) or message is None:
                break

            self.conn.on_message([message])

            self.session.incr_hits()

        socket.close()
示例#11
0
def get_car_state():
    recv_string = "error"
    with get_car_socket() as socket:
        socket.send("get_state");
        recv_string = socket.receive()
    return Response(recv_string,mimetype='application/json')
示例#12
0

class socketClient(object):
    socket = None

    def __init__(self, ip, port):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(((ip, port)))

    def send(self, msg):
        self.socket.send(msg)

    def close(self):
        self.socket.close()

    def receive(self):
        return self.socket.recv(10240)


json = '{    "glossary": {        "title": "example glossary",		"GlossDiv": {            "title": "S",			"GlossList": {                "GlossEntry": {                    "ID": "SGML",					"SortAs": "SGML",					"GlossTerm": "Standard Generalized Markup Language",					"Acronym": "SGML",					"Abbrev": "ISO 8879:1986",					"GlossDef": {                        "para": "A meta-markup language, used to create markup languages such as DocBook.",						"GlossSeeAlso": ["GML", "XML"]                    },					"GlossSee": "markup"                }            }        }    }}'

status = raw_input('Entre com o estado: ')
#status = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
json = '[msg]:' + status + '\r\n'
print json
socket = socketClient('127.0.0.1', 3001)
socket.send(json)
msg = socket.receive()
print(msg.decode('utf-8'))
socket.close()
def tracingAlg(address, count=2, interval=0.05, timeout=2, id=PID, #hadi
        hop1=1, max_hops=17, source=None, fast=False, **kwargs):
    address = resolve(address)

    socket = ICMPv4Socket(source)#ICMPv4Socket is a custom socket class
                                #creates a socket(socket.socket(family=socket.AF_INET,type=type,proto=socket.IPPROTO_ICMP))
                               #it sets for that socket a TTL and checks if broadcast support is enabled on the socket

    ttl = hop1
    dest_reached = False #true when we reach final destination
    hopsList = []#empty list

    while not dest_reached and ttl <= max_hops:
        hop_address = None # adress that the hop reached
        sentPackets = 0 #number of packets sent to final host
        recievedPackets = 0 #number of packets recieved by either current or final host

        #initializing round trip times
        #min_rtt = float('inf')#minimum round trip time
        avRTT = 0.0#average round trip time
        #max_rtt = 0.0#maximum round trip time

        for sequence in range(count):#for loop to keep varying packets sent
            req = ICMPRequest( #ICMP echo request
                                    #payload size initialized to 56
                                    #ttl initialized to 64
                destination=address,
                id=id, #id of the request(to match reply with request)
                sequence=sequence,
                ttl=ttl,#initialized in ICMPRequest to 64
                **kwargs)#traffic class

            try:
                socket.send(req)#sending request to host
                                  #raises errors such as socketunavailable and SocketBroadcastError
                sentPackets += 1

                reply = socket.receive(req, timeout)#listening for the reply of current or final hosts
                                                      #takes arguement timeout to set a timer in case socket doesn't recieve confirmation
                reply.raise_for_status()# function to make an exception if reply is not an icmp echo reply
                dest_reached = True

            except TimeExceeded:#icmplib error
                sleep(interval)#wait a given number of seconds

            except ICMPLibError:#Exception class for the icmplib package.
                continue

            hopAddress = reply.source# ip adress of the current or final host
            recievedPackets += 1 #increment packets recieved

            round_trip_time = (reply.time - req.time) * 1000# rtt in milliseconds
            avRTT += round_trip_time
            #min_rtt = min(round_trip_time, min_rtt)
            #max_rtt = max(round_trip_time, max_rtt)

            if fast:
                break

        if recievedPackets:
            avRTT = avRTT/recievedPackets #average rtt

            currentHop = Hops_Properties(#hop class created to store the properties bellow for every hop
                address=hopAddress,
                avRTT=avRTT,
                packets_sent=sentPackets,
                packets_received=recievedPackets,
                distance=ttl)

            hopsList.append(currentHop)#adding current hop to the list of hops
######################################################
        elif recievedPackets==False:
            currentHop = Hops_Properties(#hop class created to store the properties bellow for every hop
                address='Not Responding :/',
                avRTT=avRTT,
                packets_sent=sentPackets,
                packets_received=recievedPackets,
                distance=ttl)

            hopsList.append(currentHop)#adding current hop to the list of hops
########################################################
        ttl += 1#adding hop to reach the next destination

    socket.close()#closing socket

    return hopsList