Python之网络编程之UDP通信

1、简介

       UDP 是 User Datagram Protocol的简称,中文名是用户数据报协议。UDP 协议与 TCP 协议一样用于处理数据包,是一种无连接的协议。

2、服务机

import socket

udpServer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpServer.bind(('***.***.***.***', 8900))    #星号处为本机IP地址

while True:
    data, addr = udpServer.recvfrom(1024)
    print('客户端:', data.decode('utf-8'), sep='')
    info = input('我:')
    udpServer.sendto(info.encode('utf-8'), addr)

3、客户机

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    data = input('我:')
    client.sendto(data.encode('utf-8'), ('***.***.***.***', 8900))    # 星号处为客户机IP地址
    info = client.recv(1024).decode('utf-8')
    print('服务端:' + info)
发布了40 篇原创文章 · 获赞 53 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/maergaiyun/article/details/88947765