用socket进行ip之间的收发数据
>仅仅接收
import socket
# 创建socket对象
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# 准备接受的地址IP和端口
server.bind(("192.168.11.130", 8888))
while True:
(msg, address) = server.recvfrom(1024)
# 两个返回值 1:消息 2:发送端IP
print(msg.decode("utf-8"))
# 关闭资源
server.close()
>仅仅发送
import socket
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 准备发送到的地址
address = ("192.168.11.130", 8888)
while True:
msg = input(">>").encode("utf-8")
udp.sendto(msg, address)
udp.close()
>发送一次接受一次
import socket
charset = "utf-8"
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp.bind(("", 8888))
try:
while True:
msg = input("请发送数据:》》")
udp.sendto(msg.encode(charset),("192.168.11.132", 8888))
(recive, addre) = udp.recvfrom(1024)
print("接受到:%s 来自:%s" % (recive.decode(charset), addre))
finally:
udp.close()
>接受一次发送一次
import socket
charset = "utf-8"
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind(("", 8888))
try:
print("正在等待消息。。。。。")
while True:
(recive, addre) = udp.recvfrom(1024)
# print(udp.recvfrom(1024))
# print(recive.decode(charset))
# print(addre)
print("接受到:%s 来自:%s" % (recive.decode(charset), addre))
msg = input("请发数据:》》")
if msg == "quit":
break
udp.sendto(msg.encode(charset),("192.168.11.132", 8888))
finally:
udp.close()
网友评论