def close(self): if self._makefile_refs < 1: if self._sslobj: self.unwrap() socket.close(self) else: self._makefile_refs -= 1
def recv(): '''Receive messages''' while True: # If the connection is lost, properly stop the program. try: data = socket.recv(buffer_size).decode('utf8') except Exception: socket.close() print('The connection with the server has been lost') print('Press ENTER to quit the program.') exit() # If the connection has been ended properly, # just display this message and exit if data == '': print('Press ENTER to quit the program.') exit() # When receiving a message, uses this 'experimental' method to undisplay # what the user was writing and display the message instead. sys.stdout.write("\n") #Go to next line sys.stdout.write("\033[A") #Cursor up sys.stdout.write("\033[2K") #clear line sys.stdout.write(data)
def announce_bc(socket, port, name, world): '''This function acts to broadcast the server's status of operation. Whether it's alive and ready to accept new players, or dead. ''' print 'Broadcasting thread started!' dest = ('<broadcast>', port) alive = True while alive: if world.keep_alive: message = "\HELLO;"+name socket.sendto(message, dest) if not world.keep_alive: message = "\DIE" for _ in range(3): socket.sendto(message, dest) sleep(0.2) alive = False #Try to sleep up to 5 seconds before broadcasting again. for _ in range(20): if world.keep_alive: sleep(0.25) else: break print "Broadcasting thread closed!" socket.close()
def disconect_user(self, username): socket = self._active_connections.get_user_socket(username) if socket: socket.close() socket.shutdown() self._active_connections.remove_user(username)
def close(self): if self._makefile_refs < 1: self._sslobj = None socket.close(self) else: self._makefile_refs -= 1 return
def handle_client(conn): # there is one thread running this loop for each client connected signedText = conn.recv(BUFSIZ).decode('utf8') name = decrypt_msg(conn, signedText) if name == 'q' or name == '': del clients[conn] conn.close() return broadcast('{0} joined the chat'.format(name)) names[conn] = name try: while True: signedText = conn.recv(BUFSIZ).decode('utf8') msg = decrypt_msg(conn, signedText) if msg != 'q' and msg != '': broadcast('{0}: {1}'.format(name, msg)) else: del clients[conn] broadcast('{0} left the chat'.format(name)) conn.close() break except: # Exceptions from here won't be catched in main's try-catch socket.close()
def session(name, socket, aeskey): ''' handles the communication with the client ''' while True: msg = decrypt_aes(socket.recv(BUFFER_SIZE).decode('utf-8'), aeskey) if msg.startswith('PUSH*'): print('push recieved') global VERSION global FOLDER f = open( FOLDER + FILENAME.rsplit('.', 1)[0] + '_v' + str(VERSION) + '.' + FILENAME.rsplit('.', 1)[1], 'w+' ) #FILENAME.rsplit('.',1)[*] splits the extension and filename f.write(msg.split('*', 1)[1]) f.close() VERSION += 1 broadcast(msg, mode='CUSTOM') elif msg == 'QUIT': send_aes_encrypted(socket, "Quitting", aeskey) socket.close() del clients[socket] broadcast(LEFT_CHAT_MESSAGE.format(name), SYSTEM_MESSAGE_PREFIX) break else: broadcast(msg, name)
def send(socket, aeskey): while True: try: msg = input(' -> ') global FOLDER global FILENAME if not msg: continue elif msg == 'PUSH*': #push the file to server f = open(FOLDER + '\\' + FILENAME, 'rb') send_aes_encrypted(socket, msg + f.read().decode('utf-8'), aeskey) print('Push successfully') print('->', end='', flush=True) elif msg == 'PULL*': #pull the newest verison to local repo temp = open( FOLDER + "\\" + FILENAME.rsplit('.', 1)[0] + '_temp.bak', 'rb') f = open(FOLDER + '\\' + FILENAME, 'w') f.write(temp.read().decode('utf-8')) f.close() temp.close() print('pull finished') print('->', end='', flush=True) elif msg == 'debug': f = open(FOLDER + '\\' + FILENAME, 'rb') print(msg + f.read().decode('utf-8')) elif msg == 'QUIT': send_aes_encrypted(socket, msg, aeskey) print('Exitted') socket.close() else: send_aes_encrypted(socket, msg, aeskey) except OSError: break
def client(name): sock = socket(AF_INET, SOCK_STREAM) sock.connect(host, port) sock.send(name.encode()) reply = sock.recv(1024) socket.close() print('client got: [%s]' % reply)
def get_tracker_port(self) -> int: """ Connects to the tracker via TCP and receive the port to reconnect to. Returns: A port number to connect to via. """ try: socket, self_port = utils.bind_TCP_port("") socket.connect((self.tracker_addr, self.main_tracker_port)) except PortBindingException: _logger.error(f"Could select a port to bind to.") return -1 except ConnectionRefusedError as e: _logger.error( f"Could not connect to tracker node to set up individual port. Error: {str(e)}." ) return -1 msg = socket.recv(constants.MAX_BUFFER_SIZE).decode() try: port = int(msg) except ValueError: socket.close() return -1 else: socket.close() return port
def broadcast_data(self, sock, message): for socket in self._connection_list: if socket != self.sock and socket != sock: try: socket.sendall(message) except OSError: socket.close() self._connection_list.remove(socket)
def shutdown(self, completely=False): self.connect = False socket.close(self.socket) if not completely: self.ui.menu_file.entryconfigure(1, label="Reconnect", command=self.startup) self.ui.parse_output('Connection closed.')
def run(self) -> None: from robocorp_ls_core.debug_adapter_core.debug_adapter_threads import ( STOP_WRITER_THREAD, ) socket, _addr = self._server_socket.accept() self._server_socket.close() from robocorp_ls_core.debug_adapter_core.debug_adapter_threads import ( writer_thread, ) from robocorp_ls_core.debug_adapter_core.debug_adapter_threads import ( reader_thread, ) import queue from robotframework_debug_adapter_tests.fixtures import _DebuggerAPI read_from = socket.makefile("rb") write_to = socket.makefile("wb") write_queue: queue.Queue = queue.Queue() read_queue: queue.Queue = queue.Queue() writer = threading.Thread( target=writer_thread, args=(write_to, write_queue), name="Client debugger API writer", ) writer.daemon = True reader = threading.Thread( target=reader_thread, args=(read_from, read_queue.put, read_queue), name="Client debugger API reader", ) reader.daemon = True reader.start() writer.start() self.debugger_api = _DebuggerAPI( reader=reader, writer=writer, write_queue=write_queue, read_queue=read_queue, dap_resources_dir=None, ) self.started.set() try: assert self.finish.wait(5) write_queue.put(STOP_WRITER_THREAD) socket.shutdown(SHUT_WR) socket.close() except: log.exception() finally: self.sockets_closed.set()
def cleanup(self): # Clean up the connections try: for key, (socket, address) in self.connections_dict.items(): print('Closing %s connection to' % key, end=' ') print('Socket on {}:{}'.format(*address)) socket.close() finally: sys.exit(0)
def convProgress(socket): socket.listen(0) conn, addr = socket.accept() while 1: data = conn.recv(4096) if not data: break print data, sys.stderr.write("Progress thread exiting!!") socket.close()
def boardcast(client, server, SOCKET_LISTS, message): for socket in SOCKET_LISTS: if socket != client and socket != server: try: socket.send(message) except: socket.close() if socket in SOCKET_LISTS: SOCKET_LISTS.remove(socket)
def apns_send_bulk_message(registration_ids, data, **kwargs): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. """ socket = _apns_create_socket() for registration_id in registration_ids: _apns_send(registration_id, data, socket=socket, **kwargs) socket.close()
def read(socket, mask, sel): data = socket.recv(1024) logger.info("Received Message from %s", socket) if data: #If the data received is valid msgQ.put((socket, data)) #Put it in the queue else: logger.info('Closing %s', socket) #Terminate that socket sel.unregister(socket) socket.close()
def echo_client(sock, client_addr): print("Got connection from", client_addr) while True: msg = socket.recv(65536) if not msg: break socket.sendall(msg) print('Client closed connection') socket.close()
def broadcast(socket_list, server, message): """Broadcast chat message to all clients on socket_list (including sender).""" for socket in socket_list: # send the message only to peer if socket != server: try: socket.send(message.encode()) except: # broken socket connection socket.close() if socket in socket_list: socket_list.remove(socket)
def handler(signal_received, frame): # SIGINT handler prettyPrint( "sys0", getString("sigint_detected") + Style.NORMAL + Fore.RESET + getString("goodbye"), "warning") try: # Close previous socket connection (if any) socket.close() except Exception: pass _exit(0)
def handler(signal_received, frame): # SIGINT handler pretty_print( 'sys0', get_string('sigint_detected') + Style.NORMAL + Fore.RESET + get_string('goodbye'), 'warning') try: # Close previous socket connection (if any) socket.close() except Exception: pass _exit(0)
def sendResponse(responseCode, socket): print "Sending response code: ", responseCode if (responseCode == 400): socket.send("HTTP/1.0 400 Bad Request\r\n") socket.close() if (responseCode == 501): socket.send("HTTP/1.0 501 Not Implemented\r\n") socket.close() if (responseCode == 200): socket.send("HTTP/1.0 200 OK\r\n") return
def readClientMessage(self, socket): data = socket.recv(1024) if not data: socket.close() self.sockets.remove(socket) return None else: print '\tRead:', data, 'on', id(socket) tokens = string.split(data) return tokens
def close(self): ''' Correctly close the socket and free all resources. ''' global sockets if self.pthread is not None: self._stop = True if self.epid is not None: assert self.port is not None if not self.fixed: sockets.free(self.port) self.epid = None socket.close(self)
def _apns_send(token, alert, badge=0, sound="chime", content_available=False, action_loc_key=None, loc_key=None, loc_args=[], extra={}, socket=None): data = {} if action_loc_key or loc_key or loc_args: alert = {"body": alert} if action_loc_key: alert["action-loc-key"] = action_loc_key if loc_key: alert["loc-key"] = loc_key if loc_args: alert["loc-args"] = loc_args data["alert"] = alert if badge: data["badge"] = badge if sound: data["sound"] = sound if content_available: data["content-available"] = 1 data.update(extra) # convert to json, avoiding unnecessary whitespace with separators payload = json.dumps({"aps": data}, separators=(",", ":")) numBytes = len(payload) if numBytes > APNS_MAX_NOTIFICATION_SIZE: overflow = numBytes - APNS_MAX_NOTIFICATION_SIZE + 3 notificationText = data['alert'] shortenedText = notificationText[:overflow*-1] shortenedText += "..." data['alert'] = shortenedText payload = json.dumps({"aps": data}, separators=(",", ":")) if len(payload) > APNS_MAX_NOTIFICATION_SIZE: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % APNS_MAX_NOTIFICATION_SIZE) data = _apns_pack_message(token, payload) if socket: socket.write(data) #data = socket.recv(4096) #print "received message:", data else: socket = _apns_create_socket() socket.write(data) socket.close()
def connect(): # Server connection global server_ip global server_port while True: try: try: socket.close() except Exception: pass debug_output('Connecting to ' + str(server_ip) + str(':') + str(server_port)) soc = socket() soc.settimeout(SOCKET_TIMEOUT) # Establish socket connection to the server soc.connect((str(server_ip), int(server_port))) # Get server version ready = select.select([soc], [], [], SOCKET_TIMEOUT) if ready[0]: serverVersion = soc.recv(10).decode().rstrip('\n') else: raise Exception("No ver received") debug_output('Server version: ' + serverVersion) if float(serverVersion) <= float(MINER_VER): # If miner is up-to-date, display a message and continue pretty_print( 'net0', get_string('connected') + Style.NORMAL + Fore.RESET + get_string('connected_server') + str(serverVersion) + ')', 'success') break else: pretty_print( 'sys0', ' Miner is outdated (v' + MINER_VER + ') -' + get_string('server_is_on_version') + serverVersion + Style.NORMAL + Fore.RESET + get_string('update_warning'), 'warning') sleep(10) break except Exception as e: pretty_print( 'net0', get_string('connecting_error') + Style.NORMAL + ' (' + str(e) + ')', 'error') debug_output('Connection error: ' + str(e)) sleep(10) return soc
def apns_send_bulk_message(registration_ids, alert, **kwargs): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won't be included in the notification. You will need to pass None to this for silent notifications. """ socket = _apns_create_socket() for registration_id in registration_ids: _apns_send(registration_id, alert, socket=socket, **kwargs) socket.close()
def _apns_send( token, alert, badge=0, sound="chime", content_available=False, action_loc_key=None, loc_key=None, loc_args=[], extra={}, socket=None, ): data = {} if action_loc_key or loc_key or loc_args: alert = {"body": alert} if action_loc_key: alert["action-loc-key"] = action_loc_key if loc_key: alert["loc-key"] = loc_key if loc_args: alert["loc-args"] = loc_args data["alert"] = alert if badge: data["badge"] = badge if sound: data["sound"] = sound if content_available: data["content-available"] = 1 data.update(extra) # convert to json, avoiding unnecessary whitespace with separators data = json.dumps({"aps": data}, separators=(",", ":")) if len(data) > APNS_MAX_NOTIFICATION_SIZE: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (APNS_MAX_NOTIFICATION_SIZE)) data = _apns_pack_message(token, data) if socket: socket.write(data) else: socket = _apns_create_socket() socket.write(data) socket.close()
def _apns_send(token, alert, badge=0, sound="chime", content_available=False, action_loc_key=None, loc_key=None, loc_args=[], extra={}, socket=None): data = {} if action_loc_key or loc_key or loc_args: alert = {"body": alert} if action_loc_key: alert["action-loc-key"] = action_loc_key if loc_key: alert["loc-key"] = loc_key if loc_args: alert["loc-args"] = loc_args data["alert"] = alert if badge: data["badge"] = badge if sound: data["sound"] = sound if content_available: data["content-available"] = 1 data.update(extra) # convert to json, avoiding unnecessary whitespace with separators data = json.dumps({"aps": data}, separators=(",", ":")) if len(data) > APNS_MAX_NOTIFICATION_SIZE: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (APNS_MAX_NOTIFICATION_SIZE)) data = _apns_pack_message(token, data) if socket: socket.write(data) else: socket = _apns_create_socket() socket.write(data) socket.close()
def connect(): # Server connection global server_ip global server_port while True: try: try: socket.close() except Exception: pass debug_output("Connecting to " + str(server_ip) + str(":") + str(server_port)) soc = socket() soc.settimeout(SOCKET_TIMEOUT) # Establish socket connection to the server soc.connect((str(server_ip), int(server_port))) # Get server version ready = select.select([soc], [], [], SOCKET_TIMEOUT) if ready[0]: serverVersion = soc.recv(10).decode().rstrip("\n") debug_output("Server version: " + serverVersion) if float(serverVersion) <= float(MINER_VER): # If miner is up-to-date, display a message and continue pretty_print( "net0", get_string("connected") + Style.NORMAL + Fore.RESET + get_string("connected_server") + str(serverVersion) + ")", "success") break else: pretty_print( "sys0", " Miner is outdated (v" + MINER_VER + ") -" + get_string("server_is_on_version") + serverVersion + Style.NORMAL + Fore.RESET + get_string("update_warning"), "warning") sleep(10) break except Exception as e: pretty_print( "net0", get_string("connecting_error") + Style.NORMAL + " (" + str(e) + ")", "error") debug_output("Connection error: " + str(e)) sleep(10) return soc
def remove_user_presence(sock): # Remove client from online clients for client, socket in online_clients.items(): if socket == sock: del online_clients[client] # Remove client from list of users having a file open for filename, socket_list in open_files.items(): if socket in socket_list: socket_list.remove(socket) # Remove client from SOCKET_LIST try: SOCKET_LIST.remove(sock) except ValueError: pass socket.close()
def broadcast_file_list(server_socket, sock): print('Broadcasting') for client, socket in online_clients.items(): print(client) # send the message only to peer if socket != server_socket and socket != sock: try: print('socket send, data>', [rsp._FILE_LIST, list(user_dict[client])]) socket.send( rsp.make_response([rsp._FILE_LIST] + list(user_dict[client]))) except: # broken socket connection socket.close() # broken socket, remove it remove_user_presence(sock)
def Connect(): # Server connection global masterServer_address global masterServer_port while True: try: try: socket.close() except Exception: pass debugOutput("Connecting to " + str(masterServer_address) + str(":") + str(masterServer_port)) socConn = socket() # Establish socket connection to the server socConn.connect( (str(masterServer_address), int(masterServer_port))) # Get server version serverVersion = socConn.recv(3).decode().rstrip("\n") debugOutput("Server version: " + serverVersion) if (float(serverVersion) <= float(minerVersion) and len(serverVersion) == 3): # If miner is up-to-date, display a message and continue prettyPrint( "net0", getString("connected") + Style.NORMAL + Fore.RESET + getString("connected_server") + str(serverVersion) + ")", "success") break else: prettyPrint( "sys0", " Miner is outdated (v" + minerVersion + ") -" + getString("server_is_on_version") + serverVersion + Style.NORMAL + Fore.RESET + getString("update_warning"), "warning") sleep(10) break except Exception as e: prettyPrint( "net0", getString("connecting_error") + Style.NORMAL + " (" + str(e) + ")", "error") debugOutput("Connection error: " + str(e)) sleep(10) restart_miner() return socConn
def welcome(socket, address): disconnect_cnt = 0 connect_cnt = 3 # generate random aeskey of 16 # note the differences between b64 decoding aeskey = b64encode(urandom(12)).decode('utf-8') global FILENAME global FOLDER while connect_cnt != 0: # string data if (connect_cnt != 1): #no msg needed for that prase data = socket.recv(BUFFER_SIZE).decode() if connect_cnt == 3 and data.startswith( '-----BEGIN RSA PUBLIC KEY-----'): #obtain public key from the user send encrypted aes key pubkey = rsa.PublicKey.load_pkcs1(data.encode()) data = encrypt_rsa(aeskey, pubkey) socket.send(data) connect_cnt -= 1 elif connect_cnt == 2: name = decrypt_aes(data, aeskey) print(name + ' connected') # TODO: name validation clients[socket] = Client(name, socket, address, aeskey) broadcast(JOINED_CHAT_MESSAGE.format(name), SYSTEM_MESSAGE_PREFIX) connect_cnt -= 1 elif connect_cnt == 1: #transfer file FILE = open(FOLDER + FILENAME, 'rb') filemsg = '{0}*{1}'.format(FILENAME, FILE.read().decode('utf-8')) socket.send(encrypt_aes(filemsg, aeskey)) FILE.close() connect_cnt -= 1 else: # invalid connection without setting up phase disconnect_cnt += 1 if disconnect_cnt > 20: socket.send("Invalid connection.") del clients[socket] socket.close() return session(name, socket, aeskey)
def _apns_send(token, data, badge=0, sound="chime", content_available=False, custom_params={}, action_loc_key=None, loc_key=None, loc_args=[], socket=None): # data = {} #alert = {} # if action_loc_key or loc_key or loc_args: # alert = {} #{"body": alert} # if action_loc_key: # alert["action-loc-key"] = action_loc_key # if loc_key: # alert["loc-key"] = loc_key # if loc_args: # alert["loc-args"] = loc_args #data["alert"] = alert # if badge: # data["badge"] = badge # # if sound: # data["sound"] = sound # # if content_available: # data["content-available"] = 1 # convert to json, avoiding unnecessary whitespace with sepatators #data = json.dumps({"aps": data, "content": content}, separators=(",",":")) #data = json.dumps(data, separators=(",",":")) if len(data) > APNS_MAX_NOTIFICATION_SIZE: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (APNS_MAX_NOTIFICATION_SIZE)) data = _apns_pack_message(token, data) if socket: socket.write(data) else: socket = _apns_create_socket() socket.write(data) socket.close()
BACKLOG = 10 addr_info = ('127.0.0.1', 4000) def res_fun(sockfd_n): x = sockfd_n.recvfrom(100) print x[0] x = x[0][:100].split() if (x[0] == 'GET'): if (x[1] == '/apple.html'): fileo = os.getcwd() + x[1] fd = os.open(fileo, os.O_RDONLY) string = os.read(fd) while string: os.write(sockfd_n, string) string = os.read(fd) sockfd = socket() sockfd.bind(addr_info) sockfd.listen(BACKLOG) while True: (sockfd_new, from_port) = sockfd.accept() if(os.fork())== 0: socket.close(sockfd) res_fun(sockfd_new) socket.close(sockfd_new) exit(0) socket.close(sockfd_new)
from socket import socket import os sockfd = socket() sockfd.bind(('127.0.0.1',8031)) sockfd.listen(10) while True: (new_fd,from_port) = sockfd.accept() print "incoming connection" if os.fork() == 0: socket.close(sockfd) numbytes = new_fd.recv(300) print numbytes numbytes = numbytes[:100].split() print numbytes if numbytes[1] == "/": req_file = "/index.html" else: req_file = numbytes[1] fd = open(os.getcwd()+req_file) data = fd .read() s = "HTTP/1.1 200 OK\nContent-length: %d\nContent-Type: %s\n\n%s" % (len(data),"text/html",data) new_fd.send(s) new_fd.close() exit(0) socket.close(new_fd)
def close(self): socket.close(self) self.send_x = not_implemented self.recv_headers = not_implemented self.recv_content = not_implemented self.recv_chunked_content = not_implemented
""" Created on 2012-12-22 @author: Administrator """ from socket import socket HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) socket = socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(ADDR) while True: line = input('> ') if not line: break socket.send(line.encode('utf-8')) buffer = socket.recv(BUFSIZ) if not buffer: break print(buffer.decode('utf-8')) socket.close()
def close_socket_connection(socket): socket.send(mlprotocol.end_message()) socket.close()