Python socket-based simple instant messaging function example, pythonsocket

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.