Python socket-based simple instant messaging function example, pythonsocket
This example describes how Python implements simple Instant Messaging Based on socket. We will share this with you for your reference. The details are as follows:
Client tcpclient. py
#-*-Coding: UTF-8-*-import socketimport threading # target IP Address/URL and port target_host = "127.0.0.1" target_port = 9999 # create a socket object client = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # connect to the host client. connect (target_host, target_port) def handle_send (): while True: content = raw_input () client. send (content) def handle_receive (): while True: response = client. recv (4096) print responsesend_handler = threading. thread (target = handle_send, args = () send_handler.start () receive_handler = threading. thread (target = handle_receive, args = () receive_handler.start ()
Server tcpserver. py
#-*-Coding: UTF-8-*-import socketimport threading # Listening IP address and port bind_ip = "127.0.0.1" bind_port = 9999 # socket server initialization server = socket. socket (socket. AF_INET, socket. SOCK_STREAM) server. bind (bind_ip, bind_port) server. listen (5) print "[*] Listening on % s: % d" % (bind_ip, bind_port) # define the function handle_client and input the client_socketdef handle_client (): while True: request = client_socket.recv (1024) print "[*] Received: % s" % requestdef handle_send (): while True: content = raw_input () client_socket.send (content); # blocking here, wait for receiving client data client_socket, addr = server. accept () print "[*] Accept connection from: % s: % d" % (addr [0], addr [1]) # create a thread client_handler = threading. thread (target = handle_client, args = () client_handler.start () send_handler = threading. thread (target = handle_send, args = () send_handler.start ()