Python implements a simple socket program to transmit messages between two computers

Source: Internet
Author: User
This article mainly introduces how to implement a simple socket program in python to transmit messages between two computers. it involves Python socket operations and has some reference value, for more information about how to transmit messages between two computers, see the example in this article. Share it with you for your reference. The specific analysis is as follows:

Python develops a simple socket program to transmit messages between two computers, which can be divided into a client and a server. after running on the two computers, a simple message can be transmitted, you can also test it on a computer and set two different ports.

# Save as server. py server code # Message Receiverimport osfrom socket import * host = "" port = 13000buf = 1024 addr = (host, port) UDPSock = socket (AF_INET, SOCK_DGRAM) UDPSock. bind (addr) print "Waiting to receive messages... "while True: (data, addr) = UDPSock. recvfrom (buf) print "Received message:" + data if data = "exit": breakUDPSock. close () OS. _ exit (0) # Save as client. py client code # Message Senderimport osfrom socket import * host = "127.0.0.1" # set to IP address of target computerport = 13000 addr = (host, port) UDPSock = socket (AF_INET, SOCK_DGRAM) while True: data = raw_input ("Enter message to send or type 'exit ':") UDPSock. sendto (data, addr) if data = "exit": breakUDPSock. close () OS. _ exit (0)

I hope this article will help you with Python programming.

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.