current position:Home>Python socket implements UDP server and client

Python socket implements UDP server and client

2022-01-29 14:29:19 Xing Chuxin

  •        Python : 3.8.11
  •          OS : Ubuntu Kylin 20.04
  •       Conda : 4.10.1
  •     Pycharm : 2021.1.3

Code example

udp_server

  • Think about putting udp_server Change to multithreaded mode , But when looking up the materials, I saw some students say it's not necessary .
""" @Author :  First intention  @Date : 10/12/21 8:03 PM """

import socket

bind_ip = "127.0.0.1"
bind_port = 8888

# socket.AF_INET:  Network type ,IPv4
# socket.SOCK_DGRAM: UDP  client 
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# SOL_SOCKET: In use socket
# socket.SO_REUSEADDR,1 :  More meaning and function , For restart socket_server It can still go smoothly bind
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server.bind((bind_ip, bind_port))

while True:
    data = server.recvfrom(1024)
    print(data)
    server.sendto("get it!".encode("utf-8"), data[1])

# This code is unreachable
server.close()

 Copy code 

udp_client

""" @Author :  First intention  @Date : 10/12/21 8:03 PM """
import socket

server_ip = "127.0.0.1"
server_port = 8888

# socket.AF_INET:  Network type ,IPv4
# socket.SOCK_DGRAM: UDP  client 
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

client.sendto("hello world".encode("utf-8"), (server_ip, server_port))

response, address = client.recvfrom(1024)

print("response", response)
print("address", address)

#  Be aware of releasing resources 
client.close()

 Copy code 

Running effect

udp_server

  • Use IDE Forcibly ended udp_server, So there will be KeyboardInterrupt
/home/coder/anaconda3/envs/py38/bin/python /home/coder/PycharmProjects/pythonProject1/udp_server.py
(b'hello world', ('127.0.0.1', 42457))
Traceback (most recent call last):
  File "/home/coder/PycharmProjects/pythonProject1/udp_server.py", line 22, in <module>
    data = server.recvfrom(1024)
KeyboardInterrupt

Process finished with exit code 130 (interrupted by signal 2: SIGINT)

 Copy code 

udp_client

/home/coder/anaconda3/envs/py38/bin/python /home/coder/PycharmProjects/pythonProject1/udp_client.py
response b'get it!'
address ('127.0.0.1', 8888)

Process finished with exit code 0

 Copy code 

Learning recommendations


Python Open source 、 Cross platform 、 interpreted 、 Interactive and so on , Worth learning .
Python Philosophy of design : grace , clear , Simple . Advocate a way , It's better to have only one way to do one thing .
The code should be written according to the standard , It helps to communicate and understand .
Every language has a unique idea , Beginners need to change their thinking 、 Practice steadfastly 、 Keep accumulating .

copyright notice
author[Xing Chuxin],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291429168292.html