【WPF】扫描的方式发现局域网中的Android设备

C#部分

扫描局域网的IP地址范围

检查每个IP地址是否可达

csharp 复制代码
using System.Net;
using System.Net.Sockets;

public static class NetworkScanner
{
    public static List<IPAddress> ScanLocalNetwork()
    {
        List<IPAddress> devices = new List<IPAddress>();

        string localIP = GetLocalIPAddress();
        string[] ipParts = localIP.Split('.');
        string baseIP = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".";

        for (int i = 1; i < 255; i++)
        {
            string ip = baseIP + i.ToString();

            // Ping the IP address to check if it's reachable
            Ping ping = new Ping();
            PingReply reply = ping.Send(ip, 100); // Timeout set to 100ms

            if (reply.Status == IPStatus.Success)
            {
                devices.Add(IPAddress.Parse(ip));
            }
        }

        return devices;
    }

    private static string GetLocalIPAddress()
    {
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }

        return "";
    }
}

上述代码使用Ping类对局域网中的IP地址进行逐个检查,如果某个IP地址能够成功响应则认为该IP地址上有设备存在,可以将其添加到设备列表中。

一旦发现了局域网中的Android设备的IP地址,你可以使用Socket或者其他网络通信库来建立与设备的通信连接。

开始通信

csharp端建立Socket进行连接和通信:

csharp 复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public static class NetworkCommunication
{
    private const int Port = 12345; // 修改为你自己的端口号

    public static void ConnectAndCommunicate(IPAddress deviceIP)
    {
        try
        {
            // 建立Socket连接
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endPoint = new IPEndPoint(deviceIP, Port);
            socket.Connect(endPoint);

            Console.WriteLine("Connected to device: " + deviceIP);

            // 发送数据
            string message = "Hello, Android device!";
            byte[] data = Encoding.UTF8.GetBytes(message);
            socket.Send(data);

            // 接收数据
            byte[] buffer = new byte[1024];
            int bytesRead = socket.Receive(buffer);
            string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received message: " + receivedMessage);

            // 关闭连接
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

上述代码使用Socket类建立与Android设备的连接,发送一条消息,并接收设备返回的消息。你需要将Port的值修改为你自己的端口号。

Android 端

建立与WPF应用程序的连接并进行通信:

java 复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class NetworkCommunication {
    private static final String SERVER_IP = "192.168.0.100"; // 修改为你WPF应用程序所在的IP地址
    private static final int PORT = 12345; // 修改为你WPF应用程序所使用的端口号

    public static void connectAndCommunicate() {
        try {
            // 建立Socket连接
            Socket socket = new Socket(SERVER_IP, PORT);

            // 发送数据
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("Hello, WPF application!");

            // 接收数据
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String receivedMessage = in.readLine();
            System.out.println("Received message: " + receivedMessage);

            // 关闭连接
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码使用Socket类建立与WPF应用程序的连接,发送一条消息,并接收WPF应用程序返回的消息。

在你的Android应用程序中,可以调用connectAndCommunicate方法以与WPF应用程序建立连接并进行通信。

请注意,你需要将SERVER_IP修改为你WPF应用程序所在的IP地址,并将PORT修改为WPF应用程序所使用的端口号。

相关推荐
weixin199701080164 小时前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
hh95021 小时前
gent Plan x DeepSeek Harness:多 Agent 协作场景下的中央编排实践
人工智能·wpf·adg·火山引擎·agent plan·adg成都社区
Vae_Mars1 天前
WPF中的Lazy<T>使用方法
wpf
zQ.ii1 天前
WPF 触发器学习笔记
笔记·学习·wpf
SamChan901 天前
用PostgreSQL+pgvector构建PDF翻译记忆库:向量相似度检索+增量更新实战
数据库·python·ai·postgresql·pdf·wpf
李高钢2 天前
开源控件库 HandyControl 介绍与简单实践:让 WPF 界面告别“上个世纪“
开源·wpf
旋生万物3 天前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf
Now喔3 天前
WPF画刷介绍
wpf
李高钢3 天前
WPF/WinForms 客户端通过 gRPC 与后端通信:从 Proto 契约到流式调用的完整指南
wpf·grpc·winforms
一见已难忘4 天前
基于 Harmony 6.0 应用的宠物寄养预约系统实现
wpf·宠物