def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None: # Grab the banner if self.SHOULD_WAIT_FOR_SERVER_BANNER: sock.recv(2048) # Send Start TLS sock.send(self.START_TLS_CMD) if self.START_TLS_OK not in sock.recv(2048): raise StartTlsError(self.ERR_NO_STARTTLS)
def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None: sock.send(self.START_TLS_CMD) data = sock.recv(4) if not data or len(data) != 4 or data[:2] != b'\x03\x00': raise StartTlsError(self.ERR_NO_STARTTLS) packet_len = struct.unpack(">H", data[2:])[0] - 4 data = sock.recv(packet_len) if not data or len(data) != packet_len: raise StartTlsError(self.ERR_NO_STARTTLS)
def handlerequest(clientsocket: socket.socket): conn = connecttodb() cursor = conn.cursor() tagid = bytes.decode(clientsocket.recv(3)) query = 'select * from tagdata where id={0}'.format(tagid) cursor.execute(query) s=[] for (id, location, officehours, otherinfo, description) in cursor: s = [str(id)+','+location + ',', officehours + ',', otherinfo + ',', description] s.insert(0, str(len(''.join(s)))+',') clientsocket.send(bytes(''.join(s),encoding='utf8')) clientsocket.close()
def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None: # Get the SMTP banner sock.recv(2048) # Send a EHLO and wait for the 250 status sock.send(b'EHLO sslyze.scan\r\n') if b'250 ' not in sock.recv(2048): raise StartTlsError(self.ERR_SMTP_REJECTED) # Send a STARTTLS sock.send(b'STARTTLS\r\n') if b'220' not in sock.recv(2048): raise StartTlsError(self.ERR_NO_SMTP_STARTTLS)
def call(self, *args, **kwargs): """ Remote call. """ socket = Socket(AF_INET, SOCK_STREAM) socket.connect(self.address) try: method = Document() method.name = self.name method.args = args method.kwargs = kwargs socket.send(method.dump()) reply = socket.recv(4096) result = Document() result.load(reply) return result finally: socket.close()
def _initialize_telnet(connection: socket.socket) -> None: logger.info('Initializing telnet connection') # Iac Do Linemode connection.send(IAC + DO + LINEMODE) # Suppress Go Ahead. (This seems important for Putty to do correct echoing.) # This will allow bi-directional operation. connection.send(IAC + WILL + SUPPRESS_GO_AHEAD) # Iac sb connection.send(IAC + SB + LINEMODE + MODE + int2byte(0) + IAC + SE) # IAC Will Echo connection.send(IAC + WILL + ECHO) # Negotiate window size connection.send(IAC + DO + NAWS)
def get_page(server_address, request_string): try: client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server_address, REMOTE_PORT)) client_socket.send(request_string.encode()) reply = bytes() while True: part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore") # print part_body if not len(part_body): break reply += part_body finally: client_socket.close() return reply
def do_handshake(client: socket): """Get a client socket and do the handshake of it. This method receives a client socket that simulates a switch on the network and does the OpenFlow handshake process with a running controller on the network. Args: client (socket): a socket object connected to the controller. Returns: The client with the handshake process done. """ # -- STEP 1: Send Hello message client.send(Hello(xid=3).pack()) # -- STEP 2: Wait for Hello response binary_packet = b'' while len(binary_packet) < 8: binary_packet = client.recv(8) header = Header() header.unpack(binary_packet) # -- STEP 3: Wait for features_request message binary_packet = b'' # len() < 8 here because we just expect a Hello as response while len(binary_packet) < 8: binary_packet = client.recv(8) header = Header() header.unpack(binary_packet) # -- STEP 4: Send features_reply to the controller basedir = os.path.dirname(os.path.abspath(__file__)) raw_dir = os.path.join(basedir, 'raw') message = None with open(os.path.join(raw_dir, 'features_reply.cap'), 'rb') as file: message = file.read() client.send(message) return client
def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None: # Open an XMPP stream sock.send(self.XMPP_OPEN_STREAM.format(xmpp_to=self._xmpp_to).encode('utf-8')) # Get the server's features and check for an error server_resp = sock.recv(4096) if b'<stream:error>' in server_resp: raise StartTlsError(self.ERR_XMPP_REJECTED) elif b'</stream:features>' not in server_resp: # Get all the server features before initiating startTLS sock.recv(4096) # Send a STARTTLS message sock.send(self.XMPP_STARTTLS) xmpp_resp = sock.recv(2048) if b'host-unknown' in xmpp_resp: raise StartTlsError(self.ERR_XMPP_HOST_UNKNOWN) if b'proceed' not in xmpp_resp: raise StartTlsError(self.ERR_XMPP_NO_STARTTLS)
class _InProgressSocketManager(object): """ This class does not actually work right now. It's something that I'm writing that will some day replace InputThread and OutputThread and allow Autobus to function using only a single thread for each Bus instance. So it's a work in progress, and it doesn't actually work right now. """ def __init__(self): # Set up the interrupt socket interrupt_server = Socket() interrupt_server.bind(("localhost", 0)) interrupt_server.listen(1) self.interrupt_writer = Socket() self.interrupt_writer.setblocking(False) self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1]) self.interrupt_reader = interrupt_server.accept() interrupt_server.shutdown(SHUT_RDWR) interrupt_server.close() self.interrupt_reader.setblocking(False) self.interrupt_writer.setblocking(False) def loop(self): pass def run_sync(self, function, timeout=None): q = Queue() @self.run_async def new_function(): q.put(function()) try: return q.get(timeout=timeout) except Empty: raise exceptions.TimeoutException def run_async(self, function): pass def interrupt(self): self.interrupt_writer.send(0)
def connect_socket(self, sock: socket.socket) -> None: """Setup HTTP tunneling with the configured proxy. """ # Setup HTTP tunneling try: sock.connect((self._tunnel_host, self._tunnel_port)) except socket.timeout as e: raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e))) except socket.error as e: raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e))) # Send a CONNECT request with the host we want to tunnel to if self._tunnel_basic_auth_token is None: sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8')) else: sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format( self._server_host, self._server_port, self._tunnel_basic_auth_token ).encode('utf-8')) http_response = HttpResponseParser.parse_from_socket(sock) # Check if the proxy was able to connect to the host if http_response.status != 200: raise ProxyError(self.ERR_CONNECT_REJECTED)
def mysend_fully(sock: socket.socket, msg: bytes): totalsent = 0 msglen = len(msg) while totalsent < msglen: # wait until ready to send (10 seconds) rrcv, rsnd, rerr = select.select([], [sock], [], 10) if sock not in rsnd: # still not ready to send! return False # send what we can... nsent = sock.send(msg[totalsent:]) if nsent == 0: # raise RuntimeError("socket connection broken") return False totalsent = totalsent + nsent return True
def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None: sock.send(self.START_TLS_CMD) data = sock.recv(2048) if self.START_TLS_OK not in data and self.START_TLS_OK_APACHEDS not in data and self.START_TLS_OK2 not in data: raise StartTlsError(self.ERR_NO_STARTTLS + ', returned: "' + repr(data) + '"')
def socket_send(sock: socket.socket, data: str) -> int: # return socket.send(data) # Python 2 return sock.send(data.encode("ascii")) # Python 3
def threaded_client(connect: socket.socket): player = None while True: try: data = connect.recv(4096).decode() if not data: break player_data = json.loads(data) data = player_data['data'] player = game.model.players[player_data['id']] if data in [CLIENT_STARTED, CLIENT_RESET, CLIENT_STEP]: # Проверяем базовые события от клиента. if data == CLIENT_STARTED: player.is_started = True elif data == CLIENT_RESET: game.reset() elif data == CLIENT_STEP: game.player_action(player.id, data) connect.send( Response(data_class=2, data=player).json().encode('utf-8')) if data == PLAYER_BUY_WORKER: print(f'{player.id} want buy a worker.') try: game.player_action(player.id, CREATE_WORKER) except NotHaveMoney: # TODO: Добавить клиенту оповещение о том, что у него недостаточно средств. connect.send( Response(data_class=2, data=player).json().encode('utf8')) else: connect.send( Response(data_class=2, data=player).json().encode('utf8')) if data == PLAYER_BUY_WARRIOR: print(f'{player.id} want buy a warrior') try: game.player_action(player.id, CREATE_WARRIOR) except NotHaveMoney: # TODO: Добавить клиенту оповещение о том, что у него недостаточно средств. connect.send( Response(data_class=2, data=player).json().encode('utf8')) else: connect.send( Response(data_class=2, data=player).json().encode('utf8')) if data == PLAYER_ACTION_ATTACK: print(f'{player.id} want attack') game.player_action(player.id, CREATE_WAR_STEP) connect.sendall( Response(data_class=2, data=player).json().encode('utf8')) if data == PLAYER_FINISH_STEP: print(f'{player.id} want finish step') game.player_action(player.id, CREATE_FINISH_STEP) connect.sendall( Response(data_class=2, data=player).json().encode('utf8')) if data == CLIENT_AWAIT: # Проверяем, что клиент ожидает участника для игры. check_game = game.check_start_game() if check_game: players = game.chunk_active_players( chain.from_iterable([ room.get_contains_players() for room in game.rooms ])) try: if players: game_room = GameRoom() game_room.set_players(players) game.rooms.append(game_room) for player in players: player.is_started = False player.is_gaming = True connect.sendall( Response( data_class=1, data=game_room).json().encode('utf-8')) else: connect.sendall(' '.encode('utf8')) except Exception as e: logging.exception(e) connect.sendall(' '.encode('utf8')) elif player.is_gaming: for room in game.rooms: if player.id in room.get_contains_players(): connect.sendall( Response(data_class=1, data=room).json().encode('utf-8')) else: connect.send(' '.encode('utf8')) except Exception as e: logging.exception(e) break print("Lost connection") if player: game.remove_player(player) connect.close()
def send(sock: socket.socket, data: bytes): """ Implementation of the sending logic for sending data over a slow, lossy, constrained network. Args: sock -- A socket object, constructed and initialized to communicate over a simulated lossy network. data -- A bytes object, containing the data to send over the network. """ # Naive implementation where we chunk the data to be sent into # packets as large as the network will allow, and then send them # over the network, pausing half a second between sends to let the # network "rest" :) # logger = homework5.logging.get_logger("hw5-sender") chunk_size = homework5.MAX_PACKET - 1 # pause = .1 offsets = range(0, len(data), homework5.MAX_PACKET - 1) seq_num = 0 estimated_rtt = 0 dev_rtt = 0 alpha = 0.125 beta = 0.25 sample_rtt = 1 # send the chunks chunks = [data[i:i + chunk_size] for i in offsets] # print('Num of chunks: ', len(chunks)) idx = 0 buffer_size = 10 while True: # calculate timeout estimated_rtt = ((1 - alpha) * estimated_rtt) + \ (alpha * sample_rtt) dev_rtt = ((1 - beta) * dev_rtt) + \ (beta * abs(sample_rtt - estimated_rtt)) timeout_interval = estimated_rtt + (4 * dev_rtt) # send index = idx send_chunks = [] temp_seq_num = seq_num for _ in range(0, buffer_size): # print("index: ", index, "chunks.len", len(chunks) - 1) bytes_to_send = bytes([temp_seq_num]) + chunks[index] # start the timer start_time = time.time() # print('sending seq: ', seq_num) sock.send(bytes_to_send) temp_seq_num = (temp_seq_num + 1) % 256 send_chunks.append(bytes_to_send[0]) if index < len(chunks) - 1: index = index + 1 else: break # update sequence number # print('Send Chunks: ', send_chunks) # receive for _ in range(0, buffer_size): try: sock.settimeout(timeout_interval) answer = sock.recv(homework5.MAX_PACKET) # stop timer - sampled RTT sample_rtt = time.time() - start_time if answer[0] == send_chunks[0]: # print('1. receiced ack: ', answer[0]) seq_num = (seq_num + 1) % 256 if idx < len(chunks) - 1: idx = idx + 1 del send_chunks[0] # last_valid_ack = answer[0] else: break except socket.timeout: break # all acks received, increase buffer # if ((last_valid_ack + 1) == seq_num): # if buffer_size < 40: # buffer_size = buffer_size * 2 # elif buffer_size > 1: # buffer_size = buffer_size // 2 # done # print ('seq_num: ', seq_num, "len(chunks); ", len(chunks)) if seq_num == len(chunks): break
def client_chek_mail(s: socket, data): data = [int(500)] + data data = json.dumps(data) s.send((data.encode() + b'\0'))
def send(sock: socket.socket): while True: msg = input("send << ") sock.send(msg.encode(ENCODING))
def send_account_creation_status(self, connection_socket: socket, status): warn('This is deprecated.', DeprecationWarning) connection_socket.settimeout(self.timeout_seconds) status = '' + status connection_socket.send(status.encode())
def _is_dead(sock: socket) -> bool: try: sock.send(b"") return False except (ConnectionResetError, BrokenPipeError): return True
def look(sock: socket.socket): msg = str.encode("Look\n") sock.send(msg) return Action.LOOK
def incantation(sock: socket.socket): msg = str.encode("Incantation\n") sock.send(msg) return Action.INCANTATION
def set_resource(sock: socket.socket, resource: Resource): msg = str.encode("Set " + resource.value + "\n") sock.send(msg) return Action.SET
def take_resource(sock: socket.socket, resource: Resource): msg = str.encode("Take " + resource.value + "\n") sock.send(msg) return Action.TAKE
def eject(sock: socket.socket): msg = str.encode("Eject\n") sock.send(msg) return Action.EJECT
def fork(sock: socket.socket): msg = str.encode("Fork\n") sock.send(msg) return Action.FORK
def send_broadcast(sock: socket.socket, message: str): msg = str.encode("Broadcast " + message + "\n") sock.send(msg) return Action.BROADCAST
def send_requested_data(self, connection_socket: socket, requested_data): warn('This is deprecated.', DeprecationWarning) connection_socket.settimeout(self.timeout_seconds) connection_socket.send(requested_data.encode())
def send_message(sock: socket, msg: str) -> None: sock.send(msg.encode('utf-8'))
def send_respones(self, bdata: bytes, cl: socket.socket) -> Tuple[str, str]: respon, status_code, massage = self.create_respones(bdata) cl.send(respon) return status_code, massage
def _initialize_telnet(connection: socket.socket) -> None: logger.info("Initializing telnet connection") # Iac Do Linemode connection.send(IAC + DO + LINEMODE) # Suppress Go Ahead. (This seems important for Putty to do correct echoing.) # This will allow bi-directional operation. connection.send(IAC + WILL + SUPPRESS_GO_AHEAD) # Iac sb connection.send(IAC + SB + LINEMODE + MODE + int2byte(0) + IAC + SE) # IAC Will Echo connection.send(IAC + WILL + ECHO) # Negotiate window size connection.send(IAC + DO + NAWS) # Negotiate terminal type # Assume the client will accept the negociation with `IAC + WILL + TTYPE` connection.send(IAC + DO + TTYPE) # We can then select the first terminal type supported by the client, # which is generally the best type the client supports # The client should reply with a `IAC + SB + TTYPE + IS + ttype + IAC + SE` connection.send(IAC + SB + TTYPE + SEND + IAC + SE)
def send_email(s: socket, data: list): print(data) emialaddress = data[2] # setup the parameters of the message password = '******' msg = MIMEMultipart() msg['From'] = "*****@*****.**" # message msg['To'] = emialaddress if data[0] == 'forgot': msg['Subject'] = "Forget password" random_number = (random.randint(100000, 1000000)) message = ( f"\nHi Dear {data[1]}.\n\n\n your code for change password is : {random_number} ." ) print("0") url = pyqrcode.create(str(random_number)) print("1") url.png(os.getcwd() + '/Other/myqr.png', scale=10) print("2") img_data = open(os.getcwd() + '/Other/myqr.png', 'rb').read() print("3") image = MIMEImage(img_data, name=os.path.basename('myqr')) print("4") msg.attach(image) print("5") # add in the message body else: msg['Subject'] = "Subscription" random_number = (random.randint(100000, 1000000)) message = ( f"\nHi Dear {data[1]}.\n\n\n welcome to pychat! your verify code is : {random_number} ." ) url = pyqrcode.create(str(random_number)) url.png(os.getcwd() + '/Other/myqr.png', scale=10) img_data = open(os.getcwd() + '/Other/myqr.png', 'rb').read() image = MIMEImage(img_data, name=os.path.basename('myqr')) msg.attach(image) # add in the message body try: msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP('smtp.mail.yahoo.com: 587') server.starttls() server.login("*****@*****.**", password) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() data.append(random_number) if data[0] == 'forgot': data1 = [int(509)] + data # email_verify data1 = json.dumps(data1) # etelaat daryafti avalie + code random s.send((data1.encode() + b'\0')) data1 = [int(502), "Plaese check youre Email."] data1 = json.dumps(data1) s.send((data1.encode() + b'\0')) else: # client_chek_mail(s,random_number) client_chek_mail(s, data) data1 = [int(502), "Plaese check youre Email."] data1 = json.dumps(data1) s.send((data1.encode() + b'\0')) except: data1 = [int(502), "Error While Sending Email !"] data1 = json.dumps(data1) s.send((data1.encode() + b'\0'))
def handle_query(self, client_socket: socket.socket): client_socket.send(str.encode(str(self.belief)))
def add_picprofile(s: socket, data: list): global f recived_f = data[5] + data[3] if bytes.fromhex(data[4]) == b"start": f = open(os.getcwd() + '/Data/' + recived_f, "wb") elif bytes.fromhex(data[4]) == b"end": print(f"file from {data[0]} recived") print(data[-1]) f.close() if data[-2] == 'p': connection = sqlite3.connect("./database.db") cursor = connection.cursor() cursor.execute("UPDATE users SET profile=? WHERE user_id=?", (recived_f, data[0])) connection.commit() connection.close() data1 = [int(515)] data1 = json.dumps(data1) s.send((data1.encode() + b'\0')) else: for key, value in online_users.items(): if data[1] == value: data1 = [ int(503), (data[0], data[1], recived_f, data[-1], data[5], data[-2]) ] data1 = json.dumps(data1) key.send((data1.encode() + b'\0')) connection = sqlite3.connect("./database.db") cur = connection.cursor() if str(data[0]) > str(data[1]): tabale = str(data[0] + str(data[1])) else: tabale = str(data[1] + str(data[0])) sql = f""" CREATE TABLE IF NOT EXISTS {tabale}( sender VARCHAR (48), reciver VARCHAR(48), message VARCHAR (600), message_time DATETIME (60), message_id VARCHAR (60), message_type VARCHAR (3) ); """ cur.execute(sql) cur.execute(f"INSERT INTO {tabale} VALUES (?,?,?,?,?,?)", (data[0], data[1], recived_f, data[-1], data[5], data[-2])) connection.commit() connection.close() print( f"we recived a file from {data[0]} , server sent this file to {data[1]} " ) return connection = sqlite3.connect("./database.db") cur = connection.cursor() cur.execute( "INSERT INTO unsend VALUES (?,?,?,?,?,?)", (data[0], data[1], recived_f, data[-1], data[5], data[-2])) connection.commit() connection.close() print( f"we recived a file from {data[0]} but reciver ({data[1]}) is not online we stored this message in our data base..." ) else: f.write(codecs.decode(data[4], 'hex_codec'))
def send_data(local_socket: socket.socket, data: str): to_send = data + UtilConstants.MESSAGE_END local_socket.send(to_send.encode())
def _test_dir(conn: socket.socket): _dummy_start(conn) conn.send(b'PWD\r\n') data = conn.recv(BYTES_TO_LISTEN) assert data.decode().strip()[0] == '2' conn.send(b'MKD andresokol_test_dir\r\n') data = conn.recv(BYTES_TO_LISTEN) assert data.decode().strip()[0] == '2' conn.send(b'CWD andresokol_test_dir\r\n') data = conn.recv(BYTES_TO_LISTEN) assert data.decode().strip()[0] == '2' conn.send(b'CDUP\r\n') data = conn.recv(BYTES_TO_LISTEN) assert data.decode().strip()[0] == '2' conn.send(b'RMD andresokol_test_dir\r\n') data = conn.recv(BYTES_TO_LISTEN) assert data.decode().strip()[0] == '2' conn.send(b'CWD andresokol_test_dir\r\n') data = conn.recv(BYTES_TO_LISTEN) assert data.decode().strip()[0] != '2'
def turn_left(sock: socket.socket): msg = str.encode("Left\n") sock.send(msg) return Action.LEFT
def client_sender(nickname, client_socket: socket.socket, message_queue: queue.Queue, delete_observer_queue_queue): messageToSend = '\n>>> ** ' + nickname + ' has entered **' + "\n" write(messageToSend, client_socket, message_queue) client_socket.send('\n>>> Type /cmds to see the possible commands\n'.encode()) #just tells the user how to use the server while True: message_bytes = client_socket.recv(1024) try: message = message_bytes.decode().rstrip() except UnicodeDecodeError: messageToSend = '\n>> ** ' + nickname + ' has quit **' + "\n" write(messageToSend, client_socket, message_queue) index = userlist.index(nickname) userlist.remove(nickname) del socketlist[index] return if len(message) == 0: messageToSend = '\n>>> ** ' + nickname + ' has quit **' + "\n" #If you send a message of length 0, the server kicks you write(messageToSend, client_socket, message_queue) try: index = userlist.index(nickname) userlist.remove(nickname) del socketlist[index] except ValueError: p = 1 kicked = 1 return elif message.startswith('/nick '): new_nickname = message.replace('/nick ', '') if " " in new_nickname: client_socket.send("\n>>> No Spaces Allowed in Your Name!\n".encode()) else: #Lets users change their nickname. No spaces allowed. messageToSend = '\n>>> ** ' + nickname + ' is now known as ' + new_nickname + ' **' + "\n" write(messageToSend, client_socket, message_queue) index = userlist.index(nickname) userlist.remove(nickname) nickname = new_nickname userlist.insert(index, nickname) elif message.startswith('/ulist'): ulist = '\n'.join(userlist) messageToSend = "\n>>> User List: \n" client_socket.send(messageToSend.encode()) #shows the user that sent the command the list of users currently in the server client_socket.send(ulist.encode()) enter = "\n" client_socket.send(enter.encode()) elif message.startswith('/votekick '): kickname = message.replace("/votekick ", '') try: userlist.index(kickname) messageToSend = "\n>>> " + nickname + " wants to kick " + message[10:] + "!" + "\n" #initiates a vote to kick a specific person in the server. write(messageToSend, client_socket, message_queue) initializeVote() index2 = userlist.index(message[10:]) global votekicked votekicked = index2 except ValueError: messageToSend = "\n>>> " + kickname + " was not found." + "\n" #the person has to actually exist in the server write(messageToSend, message_queue, message_queue) elif message.startswith("/kick "): kickname = message.replace("/kick ", '') index1 = userlist.index(kickname) kick_socket = socketlist[index1] del userlist[index1] kick_socket.shutdown(socket.SHUT_RDWR) #hidden command, used to kick people whenever you want kick_socket.close() if kick_socket == client_socket: return messageToSend = "\n>>> " + userlist[index1] + " was kicked" + "\n" write(messageToSend, client_socket, message_queue) elif message.startswith('/agree'): messageToSend = nickname + " agrees!" + "\n" write(messageToSend, client_socket, message_queue) index = socketlist.index(client_socket) votelist[index] = 1 #tied to the votekick option, allows people to vote on if they want the person kicked votes = 0 global votekicked for x in votelist: if votelist[x] == 1: votes = votes + 1 if votes>(len(userlist)/2): #requires 1/2 of the server to agree kick_socket = socketlist[votekicked] kick_socket.shutdown(socket.SHUT_RDWR) kick_socket.close() #client_socket.shutdown(socket.SHUT_RDWR) #client_socket.close() messageToSend = "\n>>> " + userlist[votekicked] + " was kicked" + "\n" write(messageToSend, client_socket, message_queue) del userlist[votekicked] kicked = 1 if kick_socket == client_socket: return elif message.startswith('/pm '): pmer = message.split(' ', 2) if pmer[1] in userlist: indexr = userlist.index(pmer[1]) msg = "\n>>> PM from " + nickname + ": " + pmer[2] + "\n" #sends personal messages to a specific person. This is why there are socketlist[indexr].send(msg.encode()) #no spaces allowed in names. print(nickname + " sent '" + pmer[2] + "' to " + pmer[1]) else: msg = "\n>>>User '" + pmer[1] + "' not Found\n" client_socket.send(msg.encode()) elif message.startswith('/cmds'): messageToSend = "Commands:\n" messageToSend += "/nick [name] - Use this to rename yourself.\n" messageToSend += "/ulist - Use this to see all users in the server.\n" messageToSend += "/votekick [name] - Use this to start a vote to kick a user.\n" #just tells users how to use the server commands messageToSend += "/agree - Vote to kick another player.\n" messageToSend += "/pm [name] [message] - Send a private message to a user.\n" client_socket.send(messageToSend.encode()) elif not spam_filter(message): messageToSend = '\n>>> ' + nickname + ': ' + message + "\n" write(messageToSend, client_socket, message_queue) #sends a message to everyone in the server, as long as it isn't detected as spam else: print("Spam detected from " + nickname + ": " + message) client_socket.send("\n>>> Message Not Sent: Spam Detected\n".encode())
def return_d3(client: socket.socket): with open("d3/d3.js") as file: status = "HTTP/1.1 200 OK" t = "\r\n\r\n".join([status, file.read()]) client.send(t.encode())
def forward(sock: socket.socket): msg = str.encode("Forward\n") sock.send(msg) return Action.FORWARD
def return_data(client: socket.socket): client.send('{"data": [4, 8, 9, 3, 7, 5, 2, 6]}'.encode())
def turn_right(sock: socket.socket): msg = str.encode("Right\n") sock.send(msg) return Action.RIGHT
def get_inventory(sock: socket.socket): msg = str.encode("Inventory\n") sock.send(msg) return Action.INVENTORY
def return_html(client: socket.socket): with open("template.html") as file: status = "HTTP/1.1 200 OK" t = "\r\n\r\n".join([status, file.read()]) client.send(t.encode())
def write_utf(connection: socket.socket, msg: str): connection.send(struct.pack('>H', len(msg))) connection.send(msg.encode('utf-8'))
def return_icon(client: socket.socket): client.send("/r/n/r/n".encode())
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 DEALER = (HOSTNAME, PORTNUMBER) PLAYER = Socket(AF_INET, SOCK_STREAM) PLAYER.connect(DEALER) #The player is prompted for a guess until the secret number is found. The script for the player #then continues below: print('player is ready to guess') while True: bestguess = input('Give Password : '******'>', ANSWER) if ANSWER == 'That password is correct! Welcome.': break PLAYER.close()
def encode_and_send(client: socket.socket, msg: str): msg += ';endTCPmessage' client.send(msg.encode('utf-8'))
def send_bad_request(self, connection_socket: socket): connection_socket.settimeout(self.timeout_seconds) log(f"bad request", level=VERBOSE) msg = "ERROR - BAD REQUEST" connection_socket.send(msg.encode('utf-8')) connection_socket.close()