This article illustrates how Python implements a simple socket program to transfer messages between two computers. Share to everyone for your reference. The specific analysis is as follows:
Python developed a simple socket program between two computers to transfer messages, divided into client and server, respectively, two computers running on the simple message transmission can also be tested on a computer, set up two different ports can be.
# Save as server.py server-side code
# message Receiver
import OS from
socket import *
host = ""
port = 13000
BUF = 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 ": Break
udpsock.close ()
os._exit (0)
# Save as client.py client code
# message Sender
import OS from
socket import *
host = ' 127.0.0.1 ' # set to IP address of target computer
port = 13000
addr = (host, port)
Udpsock = socket (af_inet, sock_dgram) while
True:
data = RAW_INP UT ("Enter" to send or type ' exit ': ")
udpsock.sendto (data, addr)
if data =" Exit ":
break
UDPS Ock.close ()
os._exit (0)
I hope this article will help you with your Python programming.