def handle_client_send(sock, q, addr): """ Monitor queue for new messages, send them to client as they arrive """ while True: msg = q.get() # Get LAST message from queue if msg == None: break try: modules.send_msg(sock, msg) # Transmit a message except (ConnectionError, BrokenPipe): handle_disconnect(sock, addr) break
def handle_client(sock, addr): """ Receive data from the client via sock and echo it back """ try: msg = modules.recv_msg(sock) # Blocks until received # complete message print('{}: {}'.format(addr, msg)) modules.send_msg(sock, msg) # Blocks until sent except (ConnectionError, BrokenPipeError): print('Socket error') finally: print('Closed connection to {}'.format(addr)) sock.close()
def handle_input(sock): """ Prompt user for message and send it to server """ print("Type messages, enter to send. 'q' to quit") while True: msg = input() # Blocks if msg == 'q': sock.shutdown(socket.SHUT_RDWR) sock.close() break try: modules.send_msg(sock, msg) # Blocks until sent except (BrokenPipeError, ConnectionError): break
# Learning Python Network Programming import sys, socket import modules HOST = sys.argv[-1] if len(sys.argv) > 1 else '127.0.0.1' PORT = modules.PORT if __name__ == '__main__': while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('\nConnected to {}:{}'.format(HOST, PORT)) print("Type message, enter to send, 'q' to quit") msg = input() if msg == 'q': break sock.connect((HOST, PORT)) modules.send_msg(sock, msg) # Blocks until sent print('Sent message: {}'.format(msg)) msg = modules.recv_msg(sock) # Block until # received complete print('Received echo: ' + msg) except ConnectionError: print('Socket error') break finally: sock.close() print('Closed connection to server\n')