Python Socket 编程--基于UDP的套接字
程序员文章站
2022-03-04 20:43:10
...
udp是无链接的,先启动哪一端都不会报错
udp服务端:
import socket
# TCP: 9999
# UDP:9999
HOST = '172.25.254.77'
PORT = 9999
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# 绑定端口:
server.bind((HOST, PORT))
# 不需要调用监听方法
print('等待客户端的UDP请求.....')
while True:
# 接收客户端的数据
data, addr = server.recvfrom(1024)
print("接收到客户端的信息:", data)
print("客户端的socket地址为:", addr)
recv_data = input("server>>").encode()
server.sendto(recv_data, addr)
udp客户端:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = ('172.25.254.77', 9999)
while True:
msg = input('client>>')
msg = msg.encode()
client.sendto(msg, address) # sendto() 需要两个参数,第一个参数为要发送到信息,第二个为address
print("接收到服务端的消息:", client.recv(1024))
udp套接字简单示例
服务端:
from socket import *
ip_port=('127.0.0.5',8080)
buffer_size=1024
udp_server=socket(AF_INET,SOCK_DGRAM) #数据报
udp_server.bind(ip_port)
while True:
msg,addr=udp_server.recvfrom(buffer_size)
print(msg,addr)
udp_server.sendto(msg.upper(),addr)
客户端:
from socket import *
ip_port=('127.0.0.5',8080)
buffer_size=1024
udp_client=socket(AF_INET,SOCK_DGRAM)
while True:
msg=input('>>').strip()
if not msg:continue
udp_client.sendto(msg.encode('utf-8'),ip_port)
back_msg,addr=udp_client.recvfrom(buffer_size)
print(back_msg.decode('utf-8'),addr)