Python implements a simple socket program that transmits messages between two computers

  • 2020-04-02 14:39:13
  • OfStack

This article illustrates how python implements a simple socket program to transfer messages between two computers. Share with you for your reference. Specific analysis is as follows:

Python developed a simple socket program to transfer messages between two computers, divided into client and server. After running on two computers, you can carry out simple message transmission. You can also test it on one computer and set up two different ports.


# Save as server.py  Server 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_input("Enter message to send or type 'exit': ")
  UDPSock.sendto(data, addr)
  if data == "exit":
    break
UDPSock.close()
os._exit(0)

I hope this article has helped you with your Python programming.


Related articles: