How to send a message or information from one process to another process? One way is using socket communication. There are two ways to achieve this in python: UDP and TCP.

Table of Contents

UDP

First create an UDP socket, then receive or send data, finally close the socket

  • First look at the code for sender
Sender
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import socket

def main():
  udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  
  udp_socket.sendto(b"Hello World",("127.0.0.1",8080)) # must be bytes, not str
  
  send_data = input("Please input some data: ")
  udp_socket.sendto(send_data.encode('utf-8'),("127.0.0.1",8080))
  
  udp_socket.close()
  
if __name__=='__main__':
  main()
  • Then take a look at the code for receiver
Receiver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import socket

def main():
  udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  
  local_addr = ("",8080)
  udp_socket.bind(local_addr)
  
  # the data that the socket received is a tuple, the first element is the data, second element is the address tuple
  recv_data = udp_socket.recvfrom(1024)
  
  print(recv_data[0].decode('utf-8'))
  
  udp_socket.close()

TCP