def message_handle(message, sock, serv_sock, write): """Handles incoming messages and redirects them to clients""" if message: if message[:1] == '@': notfound = 1 privatemessage = message.split(' ', 1) friend = privatemessage[0][1:len(privatemessage[0])] for user, name in USER_SOCK_DICT.items(): if friend == name: if send(user, "> " + USER_SOCK_DICT.get(sock) + ": " + message) == -1: rmv_client(sock) notfound = 0 if notfound: if send(sock, "User " + friend + " not connected\n") == -1: rmv_client(sock) else: broadcast(serv_sock, sock, write, "> " + USER_SOCK_DICT.get(sock) + ': ' + message) else: broadcast( serv_sock, sock, write, "User {} has left\n".format( USER_SOCK_DICT.get(sock) if USER_SOCK_DICT. get(sock) is not None else "Anonymous")) rmv_client(sock)
def client_handler(client_socket): try: send(client_socket, b"Welcome to my server!") while True: client_buf = receive(client_socket) print(f"[*] Receive from server: {client_buf.decode('utf-8')}") send(client_socket, run_command(client_buf.decode('utf-8'))) except Exception as e: print(f"[-] Error: {e}") client_socket.close()
def main(host, port): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client.connect((host, port)) print(f"Connecting to {host}:{port}...") while True: receive_buf = receive(client) print( f"[*] Receive from server({host}:{port}): {receive_buf.decode('utf-8')}" ) message = input(">> ") send(client, message.encode("utf-8")) except Exception as e: print(f"[-] Error: {e}") client.close()
def take_username(con, serv_sock, write, username): """Takes usernames from clients""" if not username: rmv_client(con) elif any(username == user for user in USER_SOCK_DICT.values()): if send(con, "Notunique") == -1: rmv_client(con) else: USER_SOCK_DICT[con] = username if send(con, "Unique") == -1: rmv_client(con) else: broadcast(serv_sock, con, write, "User {} has joined\n".format(username)) send(con, "User {} has joined\n".format(username))
def send_msg(self, message): """Handles sending the message and checking for exit and msg len""" if message.strip() == "exit()": self.sock.close() sys.exit() if len(message) < MAX_MSG: if send(self.sock, message) == -1: self.sock.close() sys.exit() else: print("Message too big")
def accept_client(serv_sock): """Accepts clients into the server or rejects if names aren't unique or max number of users in server""" try: con, _addr = serv_sock.accept() con.setblocking(0) if len(SOCK_LIST) >= 256: send(con, "Max # users in server reached") con.close() else: SOCK_LIST.append(con) WRITE_LIST.append(con) USER_MSG_DICT[con] = [0, bytearray()] if send(con, "You are connected\n") == -1: broadcast( serv_sock, con, WRITE_LIST, "User {} has left\n".format( USER_SOCK_DICT.get(con) if USER_SOCK_DICT. get(con) is not None else "Anonymous")) rmv_client(con) except: print("Can't accept?")
def run_sensors(): measure_time = 30 temperatures = [] humidities = [] pressures = [] gas_resistances = [] motions = [] ambient_lights = [] proximities = [] cpu_temperatures = [] while measure_time > 0: temperatures.append(bme680.read_temperature()) humidities.append(bme680.read_humidity()) pressures.append(bme680.read_pressure()) gas_resistances.append(bme680.read_gas_resistance()) motions.append(motionSensor.read_motion_state()) ambient_lights.append(apds9960.read_ambient_light()) proximities.append(apds9960.read_proximity()) cpu_temperatures.append(helper.get_cpu_temperature()) measure_time = measure_time - 1 sleep(wait_time) temperature = helper.get_avg(temperatures, 1) # C humidity = helper.get_avg(humidities, 1) # RH pressure = helper.get_avg(pressures) # Pa gas_resistance = helper.get_avg(gas_resistances) # Ohms motion = helper.get_sum(motions) ambient_light = helper.get_avg(ambient_lights) proximity = helper.get_avg(proximities) cpu_temperature = helper.get_avg(cpu_temperatures, 1) data = [ temperature, humidity, pressure, motion, gas_resistance, ambient_light, proximity, cpu_temperature ] helper.log(data) helper.send(data) helper.capture(motions)
def take_user(self, sockpeer): """Takes usernames""" username = sockpeer.readline().rstrip('\n') signal.alarm(0) if ' ' in username: print("No spaces allowed in username\n") signal.signal(signal.SIGALRM, interrupted) signal.alarm(TIMEOUT) sys.stdout.write("Enter username, max 10 chars: \n\r", ) sys.stdout.flush() elif len(username) > 10: sys.stdout.write("Username can't be more than 10 chars") signal.signal(signal.SIGALRM, interrupted) signal.alarm(TIMEOUT) sys.stdout.write("Enter username, max 10 chars: \n\r", ) sys.stdout.flush() else: if send(self.sock, username) == -1: self.sock.close() sys.exit() return username
import threading import helper if __name__ == "__main__": while True: print('key in message to send ,press q to exit. ') msg = input() if msg == 'q': break helper.send(q='hello', msg=msg)
def broadcast(serv_sock, sock, write, message): """sends messages to all clients except sending client""" for sockpeer in write: if sockpeer != serv_sock and sockpeer != sock and sockpeer is not None: if send(sockpeer, message) == -1: rmv_client(sock)