Exemplo n.º 1
0
def cleanup (arg1 = None, arg2 = None):
    global clients
    log("Cleaning up")

    running = False

    for socket in clients:
        try:
            socket.shutdown(socket.SHUT_RDWR)
        except Exception as e:
            pass
        socket.close()

    if unix_socket:
        unix_socket.shutdown(socket.SHUT_RDWR)
        unix_socket.close()
    if tcp_socket:
        tcp_socket.shutdown(socket.SHUT_RDWR)
        tcp_socket.close()

    if serial_con:
        serial_con.close()
    
    try:
        os.remove('/tmp/lights')
    except OSError, e: pass

    try:
        os.remove(config['pidfile'])
    except OSError, e: pass
Exemplo n.º 2
0
        def doSSLShutdown(self, socket):
            '''Clear the SSL part of a socket.'''
            socket.set_shutdown(ssl.SENT_SHUTDOWN | ssl.RECEIVED_SHUTDOWN)

            # Don't close the socket unless negotiation is done.
            while True:
                try:
                    socket.do_handshake()
                except ssl.WantReadError:
                    pass

                try:
                    state = socket.get_state_string()
                except AttributeError:
                    # Older pyOpenSSL
                    state = socket.state_string()

                if state == 'SSL negotiation finished successfully':
                    break

                # state is None if SSL layer does not support state string
                # so we fall back to this flag, which some of the time
                # does not produce the expected results.
                if state is None and not socket.renegotiate_pending():
                    break

                # Allow the handshake to be done.
                time.sleep(0.01)

            socket.shutdown()
Exemplo n.º 3
0
    def loop(self):
        while 1:
            # Find sockets we want to write to
            write_list = [sesh.socket\
                    for sesh in self.sessions.values()\
                    if sesh.has_tx_work()]

            # And sockets we want to read from
            read_list = [sesh.socket\
                    for sesh in self.sessions.values()]
            # If there's nothing to write, select on the command socket too
            if not len(write_list):
                read_list.append(self.cmd_socket)
            read_list.append(self.server_socket)

            # Watch for errors on the set of both
            full_list = list(set(write_list + read_list))

            to_read, to_write, error = select.select(read_list, write_list,\
                    full_list)

            if error:
                raise IOError

            for w in to_write:
                sesh = self.socket_to_session(w)
                print "Send for session {}".format(sesh.sessionid)
                sesh.do_send()

            for r in to_read:
                print "Socket is ready to read!"
                if r == self.server_socket:
                    (socket, addr) = self.server_socket.accept()
                    print "New connection from {}".format(addr)
                    sessionid = self.new_sessionid()
                    new_session = STSession(socket, addr, sessionid)
                    if (new_session):
                        print "New session: %s" % str(sessionid)
                        self.session_sockets[socket] = new_session
                        self.sessions[sessionid] = new_session
                    else:
                        print "Session creation failed"
                        socket.shutdown(SHUT_RDWR)
                        socket.close()
                elif r == self.cmd_socket:
                    data = r.recv(128)
                    if not data:
                        raise IOError
                    print "Got {} from cmd socket".format(data)
                else:
                    sesh = self.socket_to_session(r)
                    print "Receive for session {}".format(sesh.sessionid)
                    packet = sesh.do_recv()
                    if packet:
                        print "Got {}".format(packet)
                        self.rx_queue.put((sesh.sessionid, packet))
Exemplo n.º 4
0
 def _close_socket(self, socket):
     try:
         if socket:
             try:
                 socket.shutdown(socket.shutdown(socket.SHUT_RDWR))
             except socket.error, exp:
                 logging.error('Error while shutting down socket: ' + str(exp))
             socket.close()
     except socket.error, exp:
         logging.error('Error while closing socket: ' + str(exp))
Exemplo n.º 5
0
 def remove_client(self, client_address):
     print "Removing " + str(client_address)
     try:
         self._lock.acquire()
         if client_address in self._clients:
             socket = self._clients[client_address]
             del self._clients[client_address]
             socket.shutdown(socket.SHUT_RDWR)
     except:
         print "Exception closing socket for " + str(client_address)
     finally:
         self._lock.release()
Exemplo n.º 6
0
    def handle(self, socket, address):
        fd = socket.makefile()
        while True:
            line = fd.readline()
            if not line:
                break

            name, value, timestamp = line.split()
            ds = self.context.get_data_source(name)
            ds.submit(int(timestamp), float(value))

        socket.shutdown(gevent.socket.SHUT_RDWR)
        socket.close()
Exemplo n.º 7
0
def _garbage_collect_connection(socket):
    """Closes the socket if auto_delete is True and the socket is opened.

    This is an acceptable practice if you know that your Python VM implements
    garbage collection and closing sockets immediately is not a concern.
    Otherwise, it is always better (because it is predictable) to explicitly
    close the socket by calling `GatewayConnection.close()`.
    """
#    print('delete connection')
    if socket != None:
        try:
            socket.shutdown(socket.SHUT_RDWR)
            socket.close()
        except Exception:
            pass
Exemplo n.º 8
0
    def run(self):
        while True:
            ch = self.ser.read(1)
            if not ch:
                continue
            if ch < "0" or ch > "5":
                continue

            if arg:
                try:
                    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM))
                    socket.connect((IP, PORT))
                    socket.send(ch);
                    socket.shutdown(socket.SD_RDWR)
                    socket.close()
                except urllib2.URLError:
                    pass
                except urllib2.HTTPError:
                    pass
Exemplo n.º 9
0
    def handleConnection(self, socket, address):
        # the first thing we receive is the netcar id.
        f = socket.makefile("rb")
        netcarID = f.readline().strip()
        socket.send("OK\n")
        f.close()
        while 1:
            try:
                while 1:
                    c = socket.recv(1)
                    if c == "#":
                        c = socket.recv(1)
                        if c == "$":
                            c = socket.recv(1)
                            if c == "*":
                                #found start of frame delimiter!
                                break
                header = ""
		while len(header) < struct.calcsize("!BH"):
		    header += socket.recv(1)
                (type, length) = struct.unpack("!BH", header)
		msg = ""
		while len(msg) < length:
		    msg += socket.recv(1)
                # execute the registered callback function for the module.
                if type in self._modules.keys():
                    self._modules[type](netcarID, msg)
                else:
                    self._log.debug("No module for type %d"%(type))
                #socket.send("OK\n")
                
            except KeyboardInterrupt:
                socket.shutdown(2)
                self._s.close()

                sys.exit(0)
                
            self._log.info("Received message: %s"%(msg))
Exemplo n.º 10
0
 def shutdown(socket):
     try:
         socket.shutdown(0)
     except IOError:
         pass
Exemplo n.º 11
0
 def shutdown(self, how):
     self._sslobj = None
     socket.shutdown(self, how)
Exemplo n.º 12
0
'''
socket.error: [Errno 10061]
server may be shutdown
'''

'''
https://docs.python.org/2/howto/sockets.html

One way to use shutdown effectively is in an HTTP-like exchange.
The client sends a request and then does a shutdown(1).
This tells the server "This client is done sending, but can still receive."
The server can detect "EOF" by a receive of 0 bytes.
It can assume it has the complete request.
'''

'''
socket.shutdown(how)
Shut down one or both halves of the connection.
If how is SHUT_RD, further receives are disallowed.
If how is SHUT_WR, further sends are disallowed.
If how is SHUT_RDWR, further sends and receives are disallowed.
on Mac OS X, shutdown(SHUT_WR) does not allow further reads on the other end of the connection.
'''

'''
socket.error: [Errno 10048]
c:\home\thin\nuts\git\socket_learn\pairs>NETSTAT.EXE -n|grep 8800
  TCP    127.0.0.1:6060         127.0.0.1:8800         TIME_WAIT
'''

buf_size = 1
Exemplo n.º 13
0
							user = message[8:]
							username,password = user.split(",")
							login_success = "false" #initially the user is not authenticated
							for key,item in db.items():
								if key == username.decode("ascii"):#search the database for the entered username
									comp_hash = item #get the users stored password hash
									hash = crypt.crypt( password.decode("ascii"), comp_hash)#hash the entered username with the stored password
									if comp_hash == hash:#if they match
										login_success = "true"#set the authenticated value to true
							file.close()
							if login_success == "true" :
								usernames[socket] = username
							else:
								socket.send("wrng")
								clients.remove(socket)
								socket.shutdown()
								socket.close()
							#END OF AUTH
							while len(keys[socket]) < 32:
								time.sleep(0.1)
							send_message(connect_socket, "\r<Server> " + usernames[socket] + " has entered the chat!\n")
						else:
							#broadcast message
							send_message(connect_socket, "\r" +"<" + usernames[socket] + "> [" + current_time() + "] " + message)
				#END RECEIVE MESSAGE FROM CLIENT
			except:
				#if it cant rcv on socket, client must have disconnected
				try:
					send_message(socket, "\r<Server> %s has disconnected\n" % usernames[socket])
					print "%s has disconnected" % usernames[socket]
				except:
Exemplo n.º 14
0
 def _shutdown(self, socket):
     try:
         socket.shutdown(0)
     except IOError:
         pass
Exemplo n.º 15
0
# Got a hello world
recieved = recv_one_message(client)
if recieved == "Hello qgis":
    print("Got hello message {}".format(recieved))
    print("Sending some commands now..")

    data = dict(command="new-layer",
                name="my layer",
                type="Point?crs=epsg:4326"
                )
    send_one_message(client, data)

    time.sleep(1.2)
    data = dict(command="other")
    send_one_message(client, data)

    time.sleep(1.2)
    data = dict(command="new-layer",
                name="my layer 2",
                type="Linestring?crs=epsg:4326"
    )
    send_one_message(client, data)

try:
    socket.shutdown(socket.SHUT_RDWR)
except:
    pass

socket.close()

Exemplo n.º 16
0
# this will run forever until the the socket closes / client disconnects / error in socket occurs
while True:
    try:
        connection, addr = socket.accept()
        worker = Thread(target=listenForBytes, args=(connection,multiWrite))
        worker.setDaemon(True)
        worker.start()

        print "Got connection from %s %s" % (connection, addr)              

    except ValueError:
        print "ERROR IN MAIN WHILE LOOP: ", ValueError
        print "Now shutting down socket and closing it."

        # The constants SHUT_RD, SHUT_WR, SHUT_RDWR have the values 0, 1, 2,
        # respectively, and are defined in <sys/socket.h> since glibc-2.1.91.
        socket.shutdown(2)  
        socket.close
        break