socket

使用udp传输数据

from socket import *

udpSocket = socket(AF_INET, SOCK_DGRAM)

#使用udp发送的数据,在每一次的是都需要写上接收方的ip和port

udpSocket.sendto("haha", ("192.168.119.210", 8080))

udpSocket.sendto(b"haha1", ("192.168.119.210", 8080))

#python3 在传输数据时需要写上b

IP 端口绑定

udpSocket.bind(("", 7788))    #两个括号

#ip端口绑定,绑定后将使用这个端口收发数据(1~1023为特定端口,有特定的程序使用,1024-65535这些端口随便使用)

python3中发送数据

**destIp = input("请输入目的ip:")
destPort = int(input("请输入目的port:"))
sendData = input("请输入要发送的数据:")
udpSocket.sendto(sendData.encode("utf-8"), (destIp, destPort))
#udpSocket.sendto(sendData.encode("gb2312"), (destIp, destPort))
#指定发送数据时所用的编码方式**

python3中接收数据

from socket import *
udpSocket = socket(AF_INET, SOCK_DGRAM) 
udpSocket.bind(("", 7789))
recvData = udpSocket.recvfrom(1024)  
#最大接收1024字节
content, destInfo = recvData
#(b'hello', ('192.168.1.102', 8080)) 这是接收到的数据,cetent接收内容·,destinfo接收ip端口信息
print("content is %s"%content)
print("content is %s"%content.decode("gb2312"))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值