udp示例
server:
# -*- coding:gb2312 -*- import socket import time import struct if __name__ == "__main__": s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) host='' port=12345 s.bind((host,port)) while 1: print("wait***") message,address=s.recvfrom(1024) message=bytes.decode(message) if message != 'time': print("message error") continue secs=time.ctime() reply=str.encode(secs) s.sendto(reply,address) print("succeed")
client:
# -*- coding=gb2312 -*- import socket if __name__ == "__main__": s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) address=('127.0.0.1',12345) s.connect(address) data=b'time' s.sendall(data) buf,address=s.recvfrom(1024) buf=bytes.decode(buf) print(buf) print(address)