def accept(self): ''' modified ssl.SSLSocket.accept() of ssl.py. ''' #import pdb; pdb.set_trace() newsock, addr = socket.accept(self) self.logger.debug("Connection from {}".format(addr)) self.logger.debug("begin SSL handshake") newsock = self.context.wrap_socket( newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) self.logger.debug("end SSL handshake: ssl_ver={}({})".format( ssl.get_protocol_name(self.ssl_version), self.ssl_version)) ''' if not server_side: print(self.getpeercert()) print(self.context.get_ca_certs()) #print(self.context.check_hostname) #print(type(self.cipher())) #print(type(self.shared_ciphers())) #print(type(self.compression())) #print(self.context.session_stats()) ''' return newsock, addr
def accept(self): newsock, addr = socket.accept(self) try: return (SSLSocket(newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, ciphers=self.ciphers, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs), addr) except socket_error as e: newsock.close() raise e
def waitConnect(socket, port=int(sys.argv[1])): socket.bind(('', port)) socket.listen(1) con, client = socket.accept() print(client, " connected.") connected = True
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 accept_connections(socket): while True: conn, addr = socket.accept() clients[conn] = addr exchange_keys(conn) print('%s:%s has connected.' % (addr[0], addr[1])) send(conn, 'Enter your name') Thread(target=handle_client, args=(conn, )).start()
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) try: return (SSLSocket(newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, ciphers=self.ciphers, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs), addr) except socket_error as e: newsock.close() raise e
def socketAccept(socket): """ Waiting for a client accept at socket :param socket: listening socket :return: connection instance for connected client """ print('waiting for a connection') connection, client_address = socket.accept() print('connection from', client_address) return connection
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) return (SSLSocket(newsock, keyfile=self.keyfile, certfile=self.certfile), addr)
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) newsock = self.context.wrap_socket(newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) return newsock, addr
def echo_server(adress): sock = socket(AF_INET, SOCK_STREAM) sock.bind(adress) socket.listen(1) while True: client, addr = socket.accept() echo_client(client, addr) # 需要重点强调的一点是,上面的例子仅仅是为了演示内置的open()函数的一个特性,并且也只适用于基于Unix的系统。 # 如果你想将一个类文件接口作用在一个套接字并希望你的代码可以跨平台,请使用套接字对象的makefile()方法。 # 但是如果不考虑可移植性的话,那上面的解决方案会比使用makefile()性能更好一点。
def LineSensor(socket): try: while True: print 'Waiting for connection to line sensor service...' # Waiting for connection. Once receiving a connection, the function accept() returns a separate # client socket for the subsequent communication. By default, the function accept() is a blocking # one, which means it is suspended before the connection comes. clientSocket, addr = socket.accept() print '...connected to line sensor service:', addr # Print the IP address of the client connected with the server. start_time = datetime.now() next_time = datetime.now() lastCommand = '' while True: try: #print("Line Sensor Loop") score = line_follower.get_score() #print("Score:", score) if len(str(score)) > 0 and score != "None": #print("Score found, passing to score tests") pass else: #print("Score not found, continuing next iteration") continue if score == 1000 and lastCommand != '1000': try: print('Lap\n') clientSocket.send(str(score) + ";") lastCommand = '1000' #print('Current Time', datetime.now()) #print('Next Time: ', (datetime.now() + timedelta(milliseconds=250))) next_time = (datetime.now() + timedelta(milliseconds=250)) except Exception as e: print(e) raise elif next_time < datetime.now() and score != -1: try: #print("Time to send new data", score) if score <= 7: lastCommand = score clientSocket.send(str(score) + ";") next_time = (datetime.now() + timedelta(milliseconds=250)) except Exception as e: print(e) except Exception as e: print(e) except Exception as e: print(e)
def start(): socket.listen() print("Waiting for connections") while True: try: conn , addr = socket.accept() conn_list.append(conn) addr_list.append(addr) #threding rerun function with given args Thread = threading.Thread(target=client_handler, args=(conn , addr)) Thread.start() except Exception as e: print(e) break
def serve_socket(socket, request_handler, socket_reader=socket_read_json, socket_writer=socket_write_json): """Serve a single request from the given socket. This is done as follows: 1. A connection is accepted. If no connection request is received (timeout), returns None. 2. Read the request using the given socket_reader. 3. Invoke the given request_handler with the request. 4. Extract the response and return value from the object returned by the request_handler. 5. Write the response to the connection socket using the socket_writer. 6. Return the return value extracted from the object returned by the request_handler. 7. Close the socket in every case. Arguments: socket -- A socket.socket like object. Must support the accept() method that should return a tuple with the first object being a connection socket. request_handler -- A function that will handle the request received. This function should: 1. Accept one argument, the request object returned by the socket_reader. 2. Must return a HandlerResult or similar object that contains: response -- This is the response that is sent to the requester using the socket_writer. return_value -- This is returned to the caller of this function. The request_handler is called only when a request is received. Keyword Arguments: socket_reader -- The function used to read a response from the socket. socket_writer -- The function used to write the request to the socket. """ connection_socket = None return_value = None try: logging.debug('Waiting for a connection...') connection_socket, _ = socket.accept() request = socket_reader(connection_socket) if request: logging.debug('Got the following request: {}'.format(request)) handler_result = request_handler(request) socket_writer(connection_socket, handler_result.response) logging.debug('Sending the following response: {}'.format( handler_result.response)) return_value = handler_result.return_value except timeout: logging.debug('Timed out waiting for connection.') pass finally: if connection_socket: connection_socket.close() return return_value
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) return (SSLSocket(sock=newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, do_handshake_on_connect= self.do_handshake_on_connect), addr)
def handle_connections(self): socket = self.__get_socket() socket.bind(self.__get_addr()) socket.listen(2) print("Waiting for sender...") client, client_addr_sender = socket.accept() self.__set_client_addr_sender(client_addr_sender) print("%s:%s has connected as sender." % client_addr_sender) while True: msg = client.recv(self.__get_buf_size()).decode("utf8") self.put_message_on_queue(msg) if msg == "": # socket.close() break print("Waiting for receiver...") socket.listen(20) receiver, client_addr_receiver = socket.accept() self.__set_client_addr_receiver(client_addr_receiver) print("%s:%s has connected as receiver." % client_addr_receiver) self.send_data(receiver)
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) return (SSLSocket( sock=newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, do_handshake_on_connect=self.do_handshake_on_connect), addr)
def accept(self): """ Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side secure channel, and the address of the remote client. """ if not self.server_side: raise ValueError("can't accept in client-side mode") newsock, addr = socket.accept(self) newsock = self.context.wrap_socket( newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) return newsock, addr
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) try: return (SSLSocket( newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, ciphers=self.ciphers, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs), addr) except socket_error as e: newsock.close() raise e
from socket import socket, AF_INET, SOCK_STREAM sock = socket(AF_INET, SOCK_STREAM) sock.bind(("localhost", 5505)) sock.listen(1) while True: try: while self.running: try: c, addr = socket.accept() print("Connection accepted from " + repr(addr[1])) # do special stuff here... print("sending...") continue except (SystemExit, KeyboardInterrupt): print("Exiting....") service.stop_service() break except Exception as ex: print("======> Fatal Error....\n" + str(ex)) print(traceback.format_exc()) self.running = False service.stop_service() raise except (SystemExit, KeyboardInterrupt): print("Force Exiting....") service.stop_service() raise def stop_service(self): """
if player_index == 0: msg = players[1] else: msg = players[0] print("Server received: ", player) print("Server responded with: ", msg) # encodes string into a bytes object, security thing connection.sendall(pickle.dumps(msg)) print("Lost connection") print("________________________________") connection.close() def extract_meta_info_and_log(address): local_ip, port = extract_ip_and_port_as_string(address) print("Connected to local ip: " + local_ip + " on port: " + port) def extract_ip_and_port_as_string(address): return address[0], str(address[1]) current_player = 1 while True: connection, address = socket.accept() extract_meta_info_and_log(address) start_new_thread(client_thread, (connection, current_player)) current_player *= -1 socket.close()
from django.conf import settings from utils import sendMsg, recvMsg, abnormalShutdown def server_port(): return 12322 if __name__ == "__main__": # Create socket object socket = socket(AF_INET, SOCK_STREAM) # Bind socket to localhost on defined port socket.bind(('', server_port())) # Start listening socket.listen(0) while True: # Accept connections while server is alive conn, address = socket.accept() # Print connection information #print("Connection received from client address " + str(address[0]) + " on port " + str(address[1])) # Try to receive incoming message and starting time incomingMsg = recvMsg(conn) # Print message from client #print("Received from client: " + str(incomingMsg)) ser = serial.Serial(settings.TTY_PORT, '9600', timeout=5) time.sleep(2) try: ser.write(str(incomingMsg)) except:
from socket import AF_INET, SOCK_STREAM, socket socket = socket(AF_INET, SOCK_STREAM) socket.bind(('localhost', 10000)) socket.listen(1) def client_thread(conn, addr): print("hello " + str(addr[1])) while True: message = conn.recv(16).decode() if(message): print(str(addr[1]) + ": " + message) else: break while True: conn, addr = socket.accept() client_thread(conn, addr) conn.close() socket.close() #exit(0)
def accept(self): (newsock, addr) = socket.accept(self) newsock = self.context.wrap_socket(newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) return (newsock, addr)
try: socket.bind(conn) except OSError: logger.critical( 'La dirección no está disponible para ser usada como servidor') pause() sys.exit(1) except GAIError: logger.critical('No es una dirección válida.') pause() sys.exit(1) # Escuchar solamente una conexión. logger.info('Aceptando solamente una conexión') socket.listen(1) # Acceptar la conexión. c, ip = socket.accept() logger.debug('Conexión aceptada por: "%s:%d"', *ip) else: logger.debug('Conectando como cliente a la dirección "%s:%d"', *conn) try: socket.connect(conn) # Conectar como cliente. except OSError: logger.critical('Esta dirección no tiene servidor.') pause() sys.exit(1) # Crear el protocolo. logger.info('Creando el manejador para el protocolo NTP') if server: t = Transfer(c) else: t = Transfer(socket)
def handle_single_peer(self, socket: socket, connPeerId: int, queue: queue.Queue) -> None: """ Handles communication with a single socket. Args: socket: A configured TCP socket to the peer. """ # Wait for peer to reconnect (peer will drop connection, then connect to new # peer specific port) while constants.FOREVER: try: conn, addr = socket.accept() # Thread only expect a single client. socket.close() break except timeout: # Repeat indefinitely. continue # Now peer has reconnected, send it its ID. conn.send(str(connPeerId).encode()) conn.settimeout(constants.TCP_PEER_TIMEOUT_DURATION) msg_queue = [] # Initial tracker-peer handshake try: # Get the IP & port that other peers can connect with utils.append_to_message_queue(msg_queue, conn) new_peer, peer_addr, port = utils.parse_new_peer_message( msg_queue.pop(0)) self.queuey.add_peer(new_peer, (peer_addr, port)) # Get Filename and sizefrom client utils.append_to_message_queue(msg_queue, conn) id, data = utils.parse_new_file_message(msg_queue.pop(0)) # Update Chunky with new peer and new files. for file in data: _logger.warning(f"GETTING FILE: {file}") filename, chunks = file self.queuey.add_file(id, filename, chunks) self.printer.print_new_peer(id, data) # Send list of files, chunks, peers to peer. msg = utils.create_chunk_list_message(self.chunky.files) conn.send(msg) # Send list of peer -> (addr, port) to peer msg = utils.create_peer_list_message(self.queuey.peer_info) conn.send(msg) except UnexpectedMessageReceivedException as e: _logger.error( f"An error occurred in initial Peer-Tracker handshake. " f"Error: {str(e)}.") # Poll (until disconnection breaks loop) _logger.warning(f"{connPeerId} starting to loop") while constants.FOREVER: try: msg = conn.recv(constants.MAX_BUFFER_SIZE) if not msg: raise timeout try: msg_code = utils.parse_peer_message(msg) except UnexpectedMessageReceivedException as e: _logger.error( f"An unexpected Message was received from peer. " f"Error: {str(e)}") _logger.warning( f"{connPeerId} handling message: {msg_code}, {msg}") if msg_code == MessageCode.PEER_DISCONNECT: try: msg_int, msg_chunk = msg.decode().split( constants.MESSAGE_SEPARATOR, 1) peer_id = int(msg_chunk) except ValueError: _logger.error( f"Peer Disconnect message has invalid payload: {msg_chunk}." ) break _logger.warning(f"Peer {peer_id} is disconnecting.") self.queuey.disconnect(peer_id) self.printer.print_peer_disconnect( peer_id, self.chunky.get_peers_files(peer_id)) if peer_id == connPeerId: socket.close() return elif msg_code == MessageCode.PEER_ACQUIRED_CHUNK: peer_id, filename, chunk = utils.parse_peer_acquired_chunk_message( msg) self.queuey.peer_acquired_chunk(connPeerId, filename, chunk) self.printer.print_peer_acquire_chunk( connPeerId, chunk, self.chunky.get_num_chunks(filename), filename) _logger.warning(f"{connPeerId} handling queue") msgs = utils.get_messages_from_queue(queue) for m in msgs: _logger.warning(f"{connPeerId} sent message {m}.") conn.send(m) if len(msgs) == 0: _logger.warning(f"{connPeerId} queue empty.") except timeout: _logger.warning(f"{connPeerId} handling queue 2") # If messages to send to peer. msgs = utils.get_messages_from_queue(queue) for m in msgs: _logger.warning(f"{connPeerId} sent message {m}.") conn.send(m) if len(msgs) == 0: _logger.warning(f"{connPeerId} queue empty.") _logger.error(f"TRACKER THREAD DONE: {connPeerId}")
def accept(self): newsock, addr = socket.accept(self) return (SSLSocket(newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, ciphers=self.ciphers, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs), addr)
def accept_clients(self, socket: socket) -> None: for _ in range(11): conn, _ = socket.accept() Thread(target=self.on_new_client, args=(conn, )).start()
def CarController(socket): while True: print 'Waiting for connection to car controller service...' # Waiting for connection. Once receiving a connection, the function accept() returns a separate # client socket for the subsequent communication. By default, the function accept() is a blocking # one, which means it is suspended before the connection comes. clientSocket, addr = socket.accept() print '...connected to car controller service:', addr # Print the IP address of the client connected with the server. lastCmd = '' while True: msgs = '' recdata = clientSocket.recv(BUFSIZ) # Receive data sent from the client. # Analyze the command received and control the car accordingly. msgs = recdata.split(';') #print("Received", len(msgs), "new messages") for data in msgs: if not data: break if lastCmd == data: print("Last Command:", lastCmd, "Current Data:", data, "Ignoring") break if data == ctrl_cmd[0]: print 'motor moving forward' motor.forward() elif data == ctrl_cmd[1]: print 'recv backward cmd' motor.backward() elif data == ctrl_cmd[2]: print 'recv left cmd' car_dir.turn_left() elif data == ctrl_cmd[3]: print 'recv right cmd' car_dir.turn_right() elif data == ctrl_cmd[6]: print 'recv home cmd' car_dir.home() elif data == ctrl_cmd[4]: print 'recv stop cmd' motor.ctrl(0) elif data == ctrl_cmd[5]: print 'read cpu temp...' temp = cpu_temp.read() tcpCliSock.send('[%s] %0.2f' % (ctime(), temp)) elif data[0:5] == 'speed': #print data numLen = len(data) - len('speed') if numLen == 1 or numLen == 2 or numLen == 3: tmp = data[-numLen:] #print 'tmp(str) = %s' % tmp spd = int(tmp) #print 'spd(int) = %d' % spd if spd < 24: spd = 24 motor.setSpeed(spd) elif data[0:8] == 'network=': print 'network =', data spd = data.split('=')[1] try: spd = int(spd) os.system('sudo tc qdisc del dev wlan0 root') os.system( 'sudo tc qdisc add dev wlan0 root netem delay {0}ms' .format(spd)) except: print 'ERROR , speed =', spd elif data[0:7] == 'offset=': print 'offset called, data = ', data offset = int(data[7:]) + 28 car_dir.calibrate(offset) elif data[0:8] == 'forward=': #print 'data =', data spd = data.split('=')[1] try: spd = int(spd) motor.setSpeed(spd) motor.forward() except: print 'Error speed =', spd elif data[0:9] == 'backward=': #print 'data =', data spd = data.split('=')[1] try: spd = int(spd) motor.setSpeed(spd) motor.backward() except: print 'ERROR , speed =', spd else: print 'Command Error! Cannot recognize command: ' + data
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR import pickle from time import sleep socket = socket(AF_INET, SOCK_STREAM) socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) socket.bind(("", 2001)) socket.listen(2) print("Server running...") player1, player1_addr = socket.accept() # accept player1 print(f"{player1_addr[0]} has been connected") player2, player2_addr = socket.accept() # accept player2 print(f"{player2_addr[0]} has been connected") player1_win = False player2_win = False player1_shot = 0 player2_shot = 0 player1_coordinates = pickle.loads(player1.recv(1024)) # recv player1 ship coordinates player2_coordinates = pickle.loads(player2.recv(1024)) # recv player2 ship coordinates while True: # send ready to player1 if player2_win: player1.send(pickle.dumps(["You lose", player1_shot, player2_shot])) player2.send(pickle.dumps(["You win", player1_shot, player2_shot])) else: