SoFunction
Updated on 2024-11-21

python implement a simple udp communication sample code

What is a Socket?

Socket, also known as "socket", the application program usually through the "socket" to the network to send requests or answer network requests, so that the host or a computer process can communicate between.

python create socket

([family[, type[, proto]]])
Parameter parsing:
family: AF_UNIX (for cross-machine communication) or AF_INET(IPv4) (for local communication)
type: type of socket, can be classified as SOCK_STREAM(TCP) or SOCK_DGRAM(UDP) depending on whether it is connection oriented or non-connection.
protocol: Default is 0.

Client code: udp_client.py

Step 1: Import the socket module and create sockets

import socket
u_client = (socket.AF_INET, socket.SOCK_DGRAM) 

Step 2: Start communication

# () Returns the socket's own address.
print("%s:%s Start working" %u_client.getsockname())

while True:
  # Send data
  data = input("input>>>")
  u_client.sendto(('utf-8'), ("localhost", 8887)) 


  # Exit system operations
  if data == 'exit':
    break

  # Receive data
  data, addr = u_client.recvfrom(1024)
  print("Source of information received by the client: %s:%s" %addr)
  print("Client received message data: %s" %('utf-8'))

Step 3: Close the socket

u_client.close()

Server-side code: udp_server.py

Step 1: Import the socket module and create sockets

import socket
u_server = (socket.AF_INET, socket.SOCK_DGRAM) 

Step 2: Start communication

# Bind ports
u_server.bind(('localhost', 8887))

print("%s:%s Start working" %u_server.getsockname())

while True:
  # Receive data
  # u_server.recvfrom() receive UDP data, return value is (data,address)
  data, addr = u_server.recvfrom(1024)
  print("Source of incoming message: %s:%s" %addr)
  print("Received message data: %s" %('utf-8'))

  # Send original address data
  send_data = ("Data received:"+('utf-8')+" --Thanks").encode('utf-8')
  u_server.sendto(send_data, addr)

  # Exit system operations
  if(('utf-8') == 'exit'):
    break

Step 3: Close the socket

u_server.close()

Test results

Create two new cmd windows, divided into executing client-side and server-side code

This is the whole content of this article.