python學習筆記(46) 基於udp協議的socket
阿新 • • 發佈:2018-11-10
udp的sever不需要監聽也不需要建立連線
啟動後只能被動等待客戶端發訊息過來
客戶端傳送訊息的同時還自帶地址資訊
回覆訊息的時候不僅需要傳送訊息,還要把對方的地址填上
SEVER:
import socket
sk = socket.socket(type=socket.SOCK_DGRAM) #datagram
sk.bind(('127.0.0.1',8080))
while 1:
msg,addr = sk.recvfrom(1024)
print(addr)
print(msg.decode('utf-8'))
info = input('>>>').encode('utf-8')
sk.sendto(info,addr)
sk.close()
CLIENT1:
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8080) #ip和埠號的元組
while 1:
info = input('二哥:')
info = ('\33[32m來自二哥的訊息:%s\33[0m'%info).encode('utf-8')
sk.sendto(info,ip_port)
ret,addr = sk.recvfrom(1024)
print(ret.decode('utf-8'))
sk.close()
CLIENT2:
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8080) #ip和埠號的元組
while 1:
info = input('泰哥:')
info = ('\33[34m來自泰哥的訊息:%s\33[0m' % info).encode('utf-8')
sk.sendto(info,ip_port)
ret,addr = sk.recvfrom(1024)
print(ret.decode('utf-8'))
sk.close()