Esempio n. 1
0
def send(socket):
    while True:
        try:
            message = input()
            # выход из чата после сообщения !exit
            # if message == "!exit":
            #     exit(0)
            #     socket.shutdown(socket.SHUT_RDWR)
            #     socket.close()
            #     return

            if message:
                # Закодировать сообщение в байты. Подготовить заголовок и преобразовать в байты,
                # как для имени пользователя ранее, затем отправить
                message1 = message
                message = message.encode(CODE)
                msg_header = f"{len(message):<{HEADER_LEN}}".encode(CODE)
                socket.send(msg_header + message)
                if message1 == "!exit":
                    socket.shutdown(socket.SHUT_RDWR)
                    socket.close()
                    exit(0)
                    return


        except EOFError as e:
            continue

        except:
            # socket.shutdown(socket.SHUT_RDWR)
            # socket.close()
            exit(0)
            return
Esempio 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()
Esempio n. 3
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
Esempio n. 4
0
def handler(socket, client):
    while True:
        message = receive(socket)
        local_time = str(int(time.time())).encode(CODE)
        l_time_header = f"{len(local_time):<{HEADER_LEN}}".encode(CODE)
        sender_time = {"header": l_time_header, "data": local_time}
        if not message or message['data'].decode(CODE) == "!exit":
            # Клиент отключился, удаляем его
            try:
                print(
                    f"Connection was closed by {clients_list[socket]['data'].decode(CODE)}"
                )
                del clients_list[socket]
                socket.shutdown(socket.SHUT_RDWR)
                socket.close()
                continue
            except:
                continue
        server_time = time.strftime("%H:%M", time.gmtime())
        print(
            f"Received message at {server_time} from {client['data'].decode(CODE)}: {message['data'].decode(CODE)}"
        )
        for client_sock in clients_list:
            if client_sock != socket:
                # Мы повторно используем здесь заголовок сообщения, отправленный отправителем, и сохраненный
                # Заголовок имени пользователя, отправленный пользователем при подключении
                client_sock.send(client['header'] + client['data'] +
                                 message['header'] + message['data'] +
                                 sender_time['header'] + sender_time['data'])
Esempio n. 5
0
def socks_selection(socket):
    client_version = ord(socket.recv(1))
    print "[+] client version : %d" % (client_version)
    if not client_version == SOCKS_VERSION:
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
        return (False, ERROR_VERSION)
    support_method_number = ord(socket.recv(1))
    print "[+] Client Supported method number : %d" % (support_method_number)
    support_methods = []
    for i in range(support_method_number):
        method = ord(socket.recv(1))
        print "[+] Client Method : %d" % (method)
        support_methods.append(method)
    selected_method = None
    for method in ALLOWED_METHOD:
        if method in support_methods:
            selected_method = 0
    if selected_method == None:
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
        return (False, ERROR_METHOD)
    print "[+] Server select method : %d" % (selected_method)
    response = chr(SOCKS_VERSION) + chr(selected_method)
    socket.send(response)
    return (True, socket)
Esempio n. 6
0
 def _close_socket(self, socket):
     try:
         socket.shutdown()
     except:
         pass
     try:
         socket.close()
     except:
         pass
Esempio n. 7
0
def handler(signal, none):
        print("\r!! FERMETURE DU SERVEUR !!")
        for socket in socketlist:   #on ferme chaque socket disponible
                if socket != server and socket != server_web:
                        user = socket.getpeername()
                        print("{} a été déconnecté {}".format(client[user], user))
                socket.shutdown(SHUT_RDWR)
                socket.close()
        sys.exit()                  #on exit le programme
    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))
Esempio n. 9
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))
Esempio n. 10
0
 def close_socket(self, connection):
     socket = self.SOCKET
     try:
         socket.shutdown(socket.SHUT_RDWR)
     except:
         pass
     try:
         connection.close()
     except:
         pass
Esempio n. 11
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))
Esempio n. 12
0
 def send(self, socket, message):
     try:
         char_sent = 0
         padded_message = pad_message(message)
         while char_sent < utils.MESSAGE_LENGTH:
             sent = socket.send(padded_message)
             char_sent = char_sent + sent
     except:
         if socket != self.socket:
             socket.shutdown(1)
             socket.close()
             self.disconnected(socket)
Esempio n. 13
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()
Esempio n. 14
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()
Esempio n. 15
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()
Esempio n. 16
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
Esempio n. 17
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
Esempio n. 18
0
def socks_selection(socket):
    """
    kiểm tra gói greeting client gởi lên ở bước 2
    SOCKS_VERSION có hổ trợ không
    AUTH_METHOD có hổ trợ không
    
    :param socket: 
    :return: 
     - tất cả có hổ trợ : return object socket, true
     - không hỗ trợ return false
    """

    # TODO: nhận gói tin với buffer là 1 byte ( byte đầu của gói request từ client) là socks version
    client_version = ord(socket.recv(1))
    print bcolors.OKBLUE +"[+] client version : %d" % (client_version) + bcolors.ENDC
    if not client_version == SOCKsDefault.SOCKS_VERSION:
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
        return (False, SOCKsError.ERROR_VERSION)

    #TODO: lấy byte tiếp theo là authen method count
    support_method_number = ord(socket.recv(1))
    print bcolors.OKBLUE +"[+] Client Supported method number : %d" % (support_method_number) + bcolors.ENDC
    support_methods = []
    for i in range(support_method_number):

        #TODO: lấy byte tiêp theo là authentication methods
        # hàm ord chuyển ký tự thành số trong asii
        # hàm chr chuyển số thành ký tự
        method = ord(socket.recv(1))
        print bcolors.OKBLUE +"[+] Client Method : %d" % (method) + bcolors.ENDC
        support_methods.append(method)
    selected_method = None
    for method in SOCKsDefault.ALLOWED_METHOD:
        if method in support_methods:
            selected_method = 0
    if selected_method == None:
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
        return (False, SOCKsDefault.ERROR_METHOD)
    print bcolors.OKBLUE+"[+] Server select method : %d" % (selected_method)+bcolors.ENDC

    #respone gói tin access no authen từ server
    response = chr(SOCKsDefault.SOCKS_VERSION) + chr(selected_method)
    socket.send(response)
    return (True, socket)
Esempio n. 19
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
Esempio n. 20
0
 def start(self):
     import socket
     ip = socket.gethostname()
     if len(csconf.servername) > 0:
         ip = csconf.servername
     print(ip)
     self.ssocket.bind((ip, csconf.port))
     self.ssocket.listen(10)
     while True:
         socket, addr = self.ssocket.accept()
         loginid = socket.recv(csconf.maxidlen)
         if not self.clients.has_key(loginid):
             print(loginid + ' login')
             user = User(loginid, socket, self.clients)
             self.clients[loginid] = user
             user.start_loop()
         else:
             errinfo = 'user' + loginid + ' has logged in, close this socket'
             socket.send(errinfo)
             socket.shutdown(2)
             socket.close()
             print(errinfo)
Esempio n. 21
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))
Esempio n. 22
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))
Esempio n. 23
0
def socks_selection(socket):
    '''Parses first request and retrieves client info (host,port,socks version and method)'''
    ''' retrieves client supported version number'''
    client_version = ord(socket.recv(1))
    print "[+] client version : %d" % client_version
    ''' checks if client supported version is supported by server'''
    if not client_version == SOCKS_VERSION:
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
        return False, ERROR_VERSION
    ''' retrieves client supported connection methods'''
    support_method_number = ord(socket.recv(1))

    print "[+] Client Supported method number : %d" % support_method_number
    ''' creates supported methods list'''
    support_methods = []
    for i in range(support_method_number):
        method = ord(socket.recv(1))
        print "[+] Client Method : %d" % method
        support_methods.append(method)
    ''' chooses method from those supported'''
    selected_method = None
    for method in ALLOWED_METHOD:
        if method in support_methods:
            selected_method = 0
    ''' checks if method was chosen '''
    if selected_method is None:
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
        return False, ERROR_METHOD
    ''' sends chosen method to client '''
    print "[+] Server select method : %d" % selected_method
    response = chr(SOCKS_VERSION) + chr(selected_method)
    socket.send(response)
    ''' returns socket if everything went well'''
    return True, socket
Esempio n. 24
0
def close():
    socket.shutdown(socket.SHUT_RDWR)
    socket.close()
    print("closed")
Esempio n. 25
0

def deNormalize(normalized, maxValue, minValue):
    deNormalized = (normalized * (maxValue - minValue) + minValue)

    return deNormalized


for (i) in range(0, 5000):

    cases = [
        [[1, 1], [0]],
        [[0, 0], [0]],
        [[1, 0], [1]],
        [[0, 1], [1]],
    ]

    for (caseNr, case) in enumerate(cases):
        inputData = case[0]
        expectedOutputData = case[1]

        # Slaapkamers, Afstand van centrum, Perceel oppervlakte, Inhoud, Tuin op zuinden, Groen
        socket.sendall(
            str("{\"command\": \"learn\", \"input\": [" + str(inputData[0]) +
                ", " + str(inputData[1]) + "], \"expectedOutput\": [" +
                str(expectedOutputData[0]) + "]}" + '\n').encode())

# Graceful shutdown
socket.shutdown(1)
socket.close()
Esempio n. 26
0
    port = kPortNumber
    socket.bind((host, port))
    socket.listen(port)
    print "socket set up"
except Exception as instance:
    print "Unable to setup a listening socket: %s" % (instance, )
    exit("1")

# this will run forever until the the socket closes / client disconnects / error in socket occurs
while True:
    try:
        connection, addr = socket.accept()
        connections.append(connection)
        log("Got connection fom %s %s" % (connection, addr))
        worker = Thread(target=listenForBytes, args=(connection, None))
        worker.setDaemon(True)
        worker.start()

        message = constructStatusMessage()
        sendMessage(connection, message)

    except ValueError:
        log("ERROR IN MAIN WHILE-LOOP: ", ValueError)
        log("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
Esempio n. 27
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









Esempio n. 28
0
host = 'localhost'
server_addr = (host, port)
'''
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
runnnig = True
Esempio n. 29
0
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 19:36:20 2019

@author: Yue
"""

import socket
import time

# set up the socket using local address
socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.bind(('localhost', 9999))
while 1:
    # get the data sent to us
    data, ip = socket.recvfrom(1024)
    # display
    print("{}: {}".format(ip, data.decode(encoding="utf-8").strip()))
    # send acknowledge with timestamp back
    now = int(round(time.time() * 1000))
    now02 = time.strftime('%Y-%m-%d %H:%M:%S ack', time.localtime(now / 1000))
    socket.sendto(now02.encode(), ip)
    if data.decode() == 'exit':
        socket.shutdown(0)
        socket.close()
        break
Esempio n. 30
0
 def shutdown(self, how):
     self._sslobj = None
     socket.shutdown(self, how)
Esempio n. 31
0
File: irc.py Progetto: d1zzy/gogbot
 def _CloseConnectionInput():
     """Closes the input part of the connection."""
     self._selector.unregister(self._conn)
     self._selector = None
     socket.shutdown(socket.SHUT_RD)
Esempio n. 32
0
 def _shutdown(self, socket):
     try:
         socket.shutdown(0)
     except IOError:
         pass
Esempio n. 33
0
 def shutdown(self, how):
     self._sslobj = None
     socket.shutdown(self, how)
Esempio n. 34
0
def close_socket(socket, how):
    try:
        socket.shutdown(how)
        socket.close()
    except:
        return
Esempio n. 35
0
 def start(self):
     buf = ''
     while True:
         ready_to_read, ready_to_write, in_error = select.select(
             self.socket_list, [], [], 0)
         for socket in ready_to_read:
             if socket == self.socket:
                 (new_socket, address) = self.socket.accept()
                 self.socket_list.append(new_socket)
             else:
                 msg = socket.recv(utils.MESSAGE_LENGTH)
                 if not msg:
                     if self.channel_dict.has_key(socket):
                         channel_name = self.channel_dict[socket]
                         self.broadcast(
                             channel_name,
                             utils.SERVER_CLIENT_LEFT_CHANNEL.format(
                                 self.username_dict[socket]) + '\n', socket)
                         self.socket_list.remove(socket)
                         del self.username_dict[socket]
                         del self.channel_dict[socket]
                         socket.shutdown(1)
                 else:
                     buf += msg
                     if len(buf) >= utils.MESSAGE_LENGTH:
                         if not self.username_dict.has_key(socket):
                             self.username_dict[socket] = buf.rstrip()
                             buf = ''
                         else:
                             username = self.username_dict[socket]
                             if buf[0] == '/':
                                 control_msg = buf[1:]
                                 if control_msg.rstrip() == 'list':
                                     response = ""
                                     for channel in self.channel_list:
                                         response += channel
                                         response += '\n'
                                     self.send(socket, response)
                                     buf = ''
                                 elif control_msg[:4] == 'join':
                                     channel_name = control_msg[5:].rstrip()
                                     buf = ''
                                     if channel_name == '':
                                         response = utils.SERVER_JOIN_REQUIRES_ARGUMENT + '\n'
                                         self.send(socket, response)
                                     elif channel_name in self.channel_list:
                                         ignore = False
                                         if self.channel_dict.has_key(
                                                 socket):
                                             old_channel_name = self.channel_dict[
                                                 socket]
                                             if old_channel_name == channel_name:
                                                 ignore = True
                                             else:
                                                 self.broadcast(
                                                     old_channel_name,
                                                     utils.
                                                     SERVER_CLIENT_LEFT_CHANNEL
                                                     .format(username) +
                                                     '\n', socket)
                                         if not ignore:
                                             self.channel_dict[
                                                 socket] = channel_name
                                             self.broadcast(
                                                 channel_name,
                                                 utils.
                                                 SERVER_CLIENT_JOINED_CHANNEL
                                                 .format(username) + '\n',
                                                 socket)
                                     else:
                                         response = utils.SERVER_NO_CHANNEL_EXISTS.format(
                                             channel_name) + '\n'
                                         self.send(socket, response)
                                 elif control_msg[:6] == 'create':
                                     channel_name = control_msg[7:].rstrip()
                                     buf = ''
                                     if channel_name == '':
                                         response = utils.SERVER_CREATE_REQUIRES_ARGUMENT + '\n'
                                         self.send(socket, response)
                                     elif channel_name in self.channel_list:
                                         response = utils.SERVER_CHANNEL_EXISTS.format(
                                             channel_name) + '\n'
                                         self.send(socket, response)
                                     else:
                                         if self.channel_dict.has_key(
                                                 socket):
                                             old_channel_name = self.channel_dict[
                                                 socket]
                                             self.broadcast(
                                                 old_channel_name,
                                                 utils.
                                                 SERVER_CLIENT_LEFT_CHANNEL.
                                                 format(username) + '\n',
                                                 socket)
                                         self.channel_list.append(
                                             channel_name)
                                         self.channel_dict[
                                             socket] = channel_name
                                 else:
                                     response = utils.SERVER_INVALID_CONTROL_MESSAGE.format(
                                         buf.rstrip()) + '\n'
                                     self.send(socket, response)
                                     buf = ''
                             elif not self.channel_dict.has_key(socket):
                                 response = utils.SERVER_CLIENT_NOT_IN_CHANNEL + '\n'
                                 self.send(socket, response)
                                 buf = ''
                             else:
                                 channel = self.channel_dict[socket]
                                 broadcast_msg = '[' + username + '] ' + buf.rstrip(
                                 ) + '\n'
                                 self.broadcast(channel, broadcast_msg,
                                                socket)
                                 buf = ''
Esempio n. 36
0
from _socket import SHUT_RD

host = '127.0.0.1'
port = 50000
size = 1024
message = ''
address = (host,port)

# Create a socket1
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the socket1 made in the server side
socket.connect(address)

# exit loop condition of user input ‘quit’
while message != 'quit':

    #get user input to send to server side
    message = input("Enter message: ") # GET http://www.google.com/ HTTP/1.1

    # send user input to server and receive in data from the server  
    socket.send(message.encode("utf-8")) # "ascii"))
    data = socket.recv(size)
    print("\n********** Message Received by Server **********")
    print(data.decode("utf-8")) # "ascii"))
    message = "quit" # Remove

# confirm client stopping and close socket1
socket.shutdown(SHUT_RD)
socket.close()
print('Quit')
Esempio n. 37
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
Esempio n. 38
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()

Esempio n. 39
0
                               socket.SOCK_DGRAM)  # socket for sending cmd
        socket.bind((local_ip, local_port))
    except OSError:
        print('Socket open error')
        sys.exit()
    tello_ip = '192.168.10.1'
    tello_port = 8889
    tello_adderss = (tello_ip, tello_port)

    socket.sendto('command'.encode('utf-8'), tello_adderss)

    try:
        index = 0
        while True:
            index += 1
            response, ip = socket.recvfrom(1024)
            if response == 'ok':
                continue
# .replace formatting gives error in python 3?
#           out = response.replace(';', ';\n')
            out = 'Tello State:\n' + str(response)
            report(out)
            sleep(INTERVAL)
    except KeyboardInterrupt:
        #       curses.echo()
        #       curses.nocbreak()
        #       curses.endwin()
        print('Closed by keyboard interrupt')
        socket.shutdown(socket.SHUT_RDWR)
        socket.close()
Esempio n. 40
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:
Esempio n. 41
0
def closeTor():
    socket.shutdown(1)
    print "Close tor"
 def shutdown(self):
     for name, socket in self.sockets.items():
         socket.shutdown(0)
         socket.close()
     self.shutdown_event.set()
Esempio n. 43
0
 def shutdown(socket):
     try:
         socket.shutdown(0)
     except IOError:
         pass
Esempio n. 44
0
s.set_inheritable(inheritable)
#

s.setblocking(flag)
# задает блокирующий или неблокирующий режим сокета

s.settimeout(value)
# задает тайм-аут для блокирующих операций сокета

s.setsockopt(level, optname, value: int)
s.setsockopt(level, optname, value: buffer)
s.setsockopt(level, optname, None, optlen: int)
# задает значение для какой-то конкретной опции сокета

s.shutdown(how)
# осуществляет остановку соединения

s.share(process_id)
#


# атрибуты данных :::::::::::::::::::::::::::::::::::::::::::::::

s.family
# семейство сокетов

s.type
# тип сокета

s.proto