python发送:
参考:https://www.cnblogs.com/reader/p/10011666.html
# -*- coding:utf-8 -*- from socket import * from time import ctime, sleep import threading class ChatRoomPlus: def __init__(self): # 全局参数配置 self.encoding = "utf-8" # 使用的编码方式 self.broadcastPort = 22222 # 广播端口 # 创建广播接收器 self.recvSocket = socket(AF_INET, SOCK_DGRAM) self.recvSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) self.recvSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) self.recvSocket.bind(('', self.broadcastPort)) # 创建广播发送器 self.sendSocket = socket(AF_INET, SOCK_DGRAM) self.sendSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # 其他 self.threads = [] def send(self): """发送广播""" print("UDP发送器启动成功...") while True: sendData="hello123" self.sendSocket.sendto(sendData.encode(self.encoding), ('255.255.255.255', self.broadcastPort)) print("【%s】%s:%s" % (ctime(), "我", sendData)) sleep(1) self.sendSocket.close() def recv(self): """接收广播""" print("UDP接收器启动成功...") while True: # 接收数据格式:(data, (ip, port)) recvData = self.recvSocket.recvfrom(1024) print("【%s】[%s : %s] : %s" % (ctime(), recvData[1][0], recvData[1][1], recvData[0].decode(self.encoding))) sleep(1) def start(self): """启动线程""" # t1 = threading.Thread(target=self.recv) t2 = threading.Thread(target=self.send) # self.threads.append(t1) self.threads.append(t2) for t in self.threads: t.setDaemon(True) t.start() while True: pass if __name__ == "__main__": demo = ChatRoomPlus() demo.start()
Android接收:
参考:https://blog.csdn.net/aino0613/article/details/73087313
需要先在AndroidManifest.xml添加权限
<uses-permission android:name="android.permission.INTERNET" />
private DatagramSocket msocketClient; private DatagramPacket Packet_Receive; private String ip; private String Port;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et1 = findViewById(R.id.EditText02); Open(); } public void Open() { System.out.println("***start***"); try { msocketClient = new DatagramSocket(null); msocketClient.setReuseAddress(true); msocketClient.bind(new InetSocketAddress(22222)); } catch (Exception e) { e.printStackTrace(); } if (msocketClient != null) { new Thread(UdpReceiver).start(); } } Runnable UdpReceiver = new Runnable() { @Override public void run() { WifiManager mwifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); WifiManager.MulticastLock lock= mwifiManager.createMulticastLock("UDPwifi"); while (true) { // System.out.println("***UdpReceiver***"); byte[] Buffer_Receive = new byte[1024]; Packet_Receive = new DatagramPacket(Buffer_Receive, 1024); if (Packet_Receive != null) { try { lock.acquire(); msocketClient.receive(Packet_Receive); int length = Packet_Receive.getLength(); if (length > 0) { final String data = new String(Buffer_Receive, 0, Packet_Receive.getLength()); // System.out.println("***data***"+data); ip=""+Packet_Receive.getAddress(); Port=""+data; // System.out.println("ip : "+Packet_Receive.getAddress()+"port :"+Packet_Receive.getPort()); runOnUiThread(new Runnable() { @Override public void run() { et1.setText("已连接"+ip+":"+Port); } }); } lock.release(); } catch (IOException e) { e.printStackTrace(); } } } } };
Android手机和电脑(运行python程序)必须在同一网络下(比如同一wifi),否则连接不上。即使手机连接的是电脑发射的热点wifi都不可以。或者使用电脑里的Android模拟机也连接不上。