基于UDP协议的socket
#server
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',8080))
msg,addr = sk.recvfrom(1024)
print(msg.decode('utf-8'))
sk.sendto(b'bye',addr)
sk.close()
#client
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8080)
sk.sendto(b'hellog',ip_port)
ret,addr = sk.recvfrom(1024)
print(ret.decode('utf-8'))
# udp的server 不需要进行监听也不需要建立连接
# 在启动服务之后只能被动的等待客户端发送消息过来
# 客户端发送消息的同时会自带地址信息
# 消息回复的时候,不需要发送信息,还需要把对方的地址发送过去
QQ的UPD聊天代码
#server
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',8080))
while True:
msg,addr = sk.recvfrom(1024)
print(addr)
print(msg.decode('utf-8'))
info = input('>>>>>>>').encode('utf-8')
sk.sendto(info,addr)
sk.close()
#tim
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8080)
while True:
info = input('Tim: ')
info = ('