A demo of the UDP transmission used python

作者: shaneZhang 分类: 互联网技术 发布时间: 2019-11-25 00:19
server.py

# -*- coding: utf-8 -*-
import ctypes
import socket
import json

# ipv4        SOCK_DGRAM指定了这个Socket的类型是UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# 绑定 客户端口和地址:
s.bind(('', 10182)
print 'Bind UDP on 10182...'
while True:
    # 接收数据 自动阻塞 等待客户端请求:
    data, addr = s.recvfrom(1024)
    message = 'Received from %s:%s.' % (addr, data)
    print message
    rData = {"message":message}
    jsonData = json.dumps(rData)
    s.sendto(jsonData.encode("utf-8"),addr)
    
client.py

# -*- coding: utf-8 -*-

import socket
import json

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 10182
network = '<broadcast>'
data = {"cmd":"device report"}
jsonData = json.dumps(data)
# 发送数据:
s.sendto(jsonData.encode("utf-8"), (network, PORT))
while True:
	data, addr = s.recvfrom(1024)
	message = 'Received from %s:%s.' % (addr, data)
	print message

本页面支持繁体中文友好显示:A demo of the UDP transmission used python

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表评论

电子邮件地址不会被公开。 必填项已用*标注