ubuntu启一个udp server,由一个client访问

1、server_8078.py代码:

python 复制代码
# udp_server.py
import socket

def start_udp_server(host, port):
    # 创建一个UDP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    # 绑定套接字到地址和端口
    server_socket.bind((host, port))
    print(f"UDP Server listening on {host}:{port}")
    
    while True:
        # 接收数据
        data, addr = server_socket.recvfrom(1024)
        print(f"Received message from {addr}: {data.decode('utf-8')}")
        
        # 发送响应
        response = "Hello from UDP server!"
        server_socket.sendto(response.encode('utf-8'), addr)

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8078
    start_udp_server(HOST, PORT)

client_8078.py代码:

python 复制代码
# udp_client.py
import socket

def start_udp_client(host, port):
    # 创建一个UDP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    try:
        # 发送数据
        message = "Hello from UDP client!"
        client_socket.sendto(message.encode('utf-8'), (host, port))
        
        # 接收响应
        data, server = client_socket.recvfrom(1024)
        print(f"Received: {data.decode('utf-8')}")
    finally:
        # 关闭套接字
        client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8078
    start_udp_client(HOST, PORT)

在第1个terminal运行:python3 server_8078.py

在第2个terminal运行:python3 client_8078.py

相关推荐
orion571 天前
Missing Semester Class1:course overview and introduction of shell
linux
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式
用户805533698032 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698032 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
七歌杜金房2 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
tntxia3 天前
linux curl命令详解_curl详解
linux
扛枪的书生3 天前
Linux 网络管理器用法速查
linux
顺风尿一寸4 天前
Java Socket 内核之旅:从 SocketChannel.read() 到 tcp_recvmsg 与 epoll 的完整调用链路
linux
XIAOHEZIcode4 天前
Ubuntu 终端美化全栈指南:Bash 到 Kitty 踩坑实录
linux·ubuntu·命令行
唐青枫4 天前
别再只会用 cron:Linux systemd Timer 定时任务实战详解
linux