示例#1
0
 def __init__(self, http: HttpConnection, stream_id: int,
              transmit: Callable[[], None]) -> None:
     self.http = http
     self.queue: asyncio.Queue[str] = asyncio.Queue()
     self.stream_id = stream_id
     self.subprotocol: Optional[str] = None
     self.transmit = transmit
     self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
    async def send(self, message: Dict) -> None:
        data = b""
        end_stream = False
        if message["type"] == "websocket.accept":
            subprotocol = message.get("subprotocol")

            self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)

            headers = [
                (b":status", b"200"),
                (b"server", SERVER_NAME.encode()),
                (b"date", formatdate(time.time(), usegmt=True).encode()),
            ]
            if subprotocol is not None:
                headers.append((b"sec-websocket-protocol", subprotocol.encode()))
            self.connection.send_headers(stream_id=self.stream_id, headers=headers)

            # consume backlog
            while self.http_event_queue:
                self.http_event_received(self.http_event_queue.popleft())

        elif message["type"] == "websocket.close":
            if self.websocket is not None:
                data = self.websocket.send(
                    wsproto.events.CloseConnection(code=message["code"])
                )
            else:
                self.connection.send_headers(
                    stream_id=self.stream_id, headers=[(b":status", b"403")]
                )
            end_stream = True
        elif message["type"] == "websocket.send":
            if message.get("text") is not None:
                data = self.websocket.send(
                    wsproto.events.TextMessage(data=message["text"])
                )
            elif message.get("bytes") is not None:
                data = self.websocket.send(
                    wsproto.events.Message(data=message["bytes"])
                )

        if data:
            self.connection.send_data(
                stream_id=self.stream_id, data=data, end_stream=end_stream
            )
        if end_stream:
            self.closed = True
        self.transmit()
    async def send(self, message: Dict) -> None:
        data = b""
        end_stream = False
        if message["type"] == "websocket.accept":
            subprotocol = message.get("subprotocol")

            self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)

            headers = [
                (b":status", b"200"),
                (b"server", SERVER_NAME.encode()),
                (b"date", formatdate(time.time(), usegmt=True).encode()),
            ]
            if subprotocol is not None:
                headers.append((b"sec-websocket-protocol", subprotocol.encode()))
            self.connection.send_headers(stream_id=self.stream_id, headers=headers)

            # consume backlog
            while self.http_event_queue:
                self.http_event_received(self.http_event_queue.popleft())

        elif message["type"] == "websocket.close":
            if self.websocket is not None:
                data = self.websocket.send(
                    wsproto.events.CloseConnection(code=message["code"])
                )
            else:
                self.connection.send_headers(
                    stream_id=self.stream_id, headers=[(b":status", b"403")]
                )
            end_stream = True
        elif message["type"] == "websocket.send":
           
            if message.get("text") is not None:
                global list_of_files
                list_of_files = []
                for entry in os.listdir("examples\\"): 
                    if ".txt" in entry:
                        list_of_files.append(entry)
                if message["text"] == "1":
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data = "Sorry I am not a registration Server. Contact RS")
                    )
                elif message["text"] == "2":
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data = "")
                    )


                if message["text"] == "listofrfcs":
                    
               
                    
                    
                    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
                    s.connect(("8.8.8.8",80))
                    ip = (s.getsockname()[0])
                    for entry in os.listdir("examples\\"):
                        if ".txt" in entry:
                            list_of_files.append(entry)
                    list_of_files = list(set(list_of_files))
                    

                    file_name_of_csv = "examples\\list_of_files.csv"
                    with open(file_name_of_csv,"w") as csvfile:
                        csvwriter = csv.writer(csvfile)
                        for i in list_of_files:
                            csvwriter.writerow([str(i)+";"+str(ip)+";"+str(4433)+";"+"1"])

                    str_of_files = ""
                    for i in list_of_files:
                        str_of_files = str_of_files + str(i) + ";"
                    
                    str_of_files = str_of_files[:-1]
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data = str_of_files)
                    )
                elif message["text"] in list_of_files:
                    global filesize
                    filesize = os.stat("examples\\"+message["text"]).st_size
                    no_of_iterations = int(filesize/1000)+1
                    global f
                    f = open("examples\\"+message["text"],'r')
                    x = f.read(1000) +";;;"+str(no_of_iterations)
                    
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data = x)
                    )
                    filesize -=40
                elif message["text"] == "next":
                    x = f.read(1000)
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data = x)
                    )
                    filesize -=1000

                    
            elif message.get("bytes") is not None:
                
                data = self.websocket.send(
                    wsproto.events.Message(data=message["bytes"])
                )

        if data:
            self.connection.send_data(
                stream_id=self.stream_id, data=data, end_stream=end_stream
            )
        if end_stream:
            self.closed = True
        self.transmit()
    async def send(self, message: Dict) -> None:
        data = b""
        end_stream = False
        if message["type"] == "websocket.accept":
            subprotocol = message.get("subprotocol")

            self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)

            headers = [
                (b":status", b"200"),
                (b"server", SERVER_NAME.encode()),
                (b"date", formatdate(time.time(), usegmt=True).encode()),
            ]
            if subprotocol is not None:
                headers.append(
                    (b"sec-websocket-protocol", subprotocol.encode()))
            self.connection.send_headers(stream_id=self.stream_id,
                                         headers=headers)

            # consume backlog
            while self.http_event_queue:
                self.http_event_received(self.http_event_queue.popleft())

        elif message["type"] == "websocket.close":
            if self.websocket is not None:
                data = self.websocket.send(
                    wsproto.events.CloseConnection(code=message["code"]))
            else:
                self.connection.send_headers(stream_id=self.stream_id,
                                             headers=[(b":status", b"403")])
            end_stream = True
        elif message["type"] == "websocket.send":
            #print("w1:",message)
            if message.get("text") is not None:
                print(message["text"])
                global list_of_peers
                list_of_peers = []
                with open("examples\\peersregistered.csv", 'r') as csvobj:
                    csv_reader = csv.reader(csvobj)
                    for row in csv_reader:
                        if len(row) >= 1:
                            list_of_peers.append(row[0])
                list_of_peers = list(set(list_of_peers))
                if message["text"] == "1":
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data=""))
                elif message["text"] == "2":
                    data = self.websocket.send(
                        wsproto.events.TextMessage(
                            data=
                            "Sorry I am not your peer. I cannot send you Files."
                        ))
                elif message[
                        "text"] == "Can you please provide me a list of active peers.":
                    peers = ""
                    for i in list_of_peers:
                        peers += str(i) + "@"
                    peers = peers[:-1]

                    data = self.websocket.send(
                        wsproto.events.TextMessage(data=peers))
                elif "I want to leave." in message["text"]:
                    list_23 = message["text"].split(";")
                    print("list of peers where i am getting error",
                          list_of_peers)
                    want_to_leave = str(list_23[1]) + ";" + str(list_23[2])
                    count_of_removing_clients = list_of_peers.count(
                        want_to_leave)
                    for i in range(count_of_removing_clients):
                        list_of_peers.remove(want_to_leave)
                    data = self.websocket.send(
                        wsproto.events.TextMessage(data="Ok. Bye"))
                    list_of_peers = list(set(list_of_peers))
                    with open("examples\\peersregistered.csv", 'w') as csvobj:
                        csv_writer = csv.writer(csvobj)
                        for i in list_of_peers:
                            if i == "":
                                pass
                            else:
                                csv_writer.writerow([i])

                elif "I want to register myself." in message["text"]:
                    data1 = message["text"]

                    list_of_send_data = data1.split("#")
                    print("data which i am receiving", list_of_send_data)
                    data_to_be_in_csv = str(list_of_send_data[1]) + ";" + str(
                        list_of_send_data[2])
                    with open("examples\\peersregistered.csv", 'a') as csvobj:
                        csv_writer = csv.writer(csvobj)
                        if data_to_be_in_csv not in list_of_peers:
                            if data_to_be_in_csv == "[]":
                                pass
                            else:
                                csv_writer.writerow([data_to_be_in_csv])

                    with open("examples\\peersregistered.csv", 'r') as csvobj:
                        csv_reader = csv.reader(csvobj)
                        for row in csv_reader:
                            list_of_peers.append(row)
                    data = self.websocket.send(
                        wsproto.events.TextMessage(
                            data="Ok. You are Registered."))

            elif message.get("bytes") is not None:

                data = self.websocket.send(
                    wsproto.events.Message(data=message["bytes"]))

        if data:
            self.connection.send_data(stream_id=self.stream_id,
                                      data=data,
                                      end_stream=end_stream)
        if end_stream:
            self.closed = True
        self.transmit()