socket编程:基于UDP的数据传输

服务器端:

import socket

HOST = ''
PORT = 10888
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
data = True
while data:
    data, address = s.recvfrom(1024)
    if data == b'bye':  # 当收到bye时退出循环
        break
    print('Received String:', data.decode('utf-8'))
    s.sendto(data, address)

s.close()

客户端:

import socket
HOST='localhost'
PORT=10888
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
data='你好'
while data:
    s.sendto(data.encode('utf-8'),(HOST,PORT))
    if data=='bye':
        break
    data,addr=s.recvfrom(512)
    print("Receive from server:\n",data.decode('utf-8'))
    data=input('Please input a info:\n')
s.close()

在这里插入图片描述
在这里插入图片描述

©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页