Server.py

import socket

port = 8080
host = 'localhost'
ADDR = (host, port)

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

udpServer.bind(ADDR)

while True:
    data, addr = udpServer.recvfrom(1024)
    replay = str(data) + '....ok'
    udpServer.sendto(replay.encode(), addr)
    print(replay)

udpServer.close()

Client.py


HOST = 'localhost'
PORT = 8080
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True:
    data = input(">")
    if not data:
        break
    udpCliSock.sendto(data.encode(), ADDR)
    data, ADDR = udpCliSock.recvfrom(BUFSIZE)
    if not data:
        break
    print('server replay...:',data)

udpCliSock.close()

udp 和 tcp 的最大区别是server 无需监听客户端的链接


FIZLIN
514 声望8 粉丝

跟我走吧,天亮就出发


« 上一篇
#网络编程