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.