server
import socket
sk = socket.socket(type=socket.SOCK_DGRAM) # 建立一个socket对象,
# 指定以UDP协议的形式来连接
sk.bind(('127.0.0.1',8080))
# 指定服务的地址
msg,addr = sk.recvfrom(1024) # 接收消息,发送端的地址
print(msg,addr)
sk.sendto(b'HELLO',addr) # 给发送端回复消息
sk.close() # 关闭socket连接
client
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.sendto(b'hello',('127.0.0.1',8080)) # 直接给服务器发送一段消息
msg,addr = sk.recvfrom(1024) # 接收对面的回信
print(msg)
sk.close()
代码优化程序
##server
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',9090))
while True:
msg,addr = sk.recvfrom(1024)
print('来自[%s:%s]的消息--%s'%(addr[0],addr[1],msg.decode('utf-8')))
inp = input('>>>')
sk.sendto(inp.encode('utf-8'),addr)
sk.close()
##client
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
addr = ('127.0.0.1',9090)
while True:
msg = input('>>>')
sk.sendto(msg.encode('utf-8'),addr)
msg_recv,addr = sk.recvfrom(1024)
print(msg_recv.decode('utf-8'))
sk.close()