V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iRubyBoy
V2EX  ›  Android

求助,请你喝一杯☕️,帮忙把 Java 的代码翻译成 iOS 版。

  •  
  •   iRubyBoy · 255 天前 · 7578 次点击
    这是一个创建于 255 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有安卓的同学会 iOS 的吗 求帮忙把下面的代码翻译成 iOS 的版本

    iOS 项目用的第三方 socket 库 GCDAsyncSocket

    import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress;

    public class teststr { public static void main(String[] args) { wakeup(); } public static void wakeup(){ String mac = "00:30:64:69:F8:A7"; //mac 地址 // String mac = "00:02:a0:01:26:84"; try {

            int port = 9;
            byte[] macByte = new byte[6];
            String[] ips = mac.split("\\:|\\-");
            for (int i = 0; i < 6; i++) {
    
                macByte[i] = (byte) Integer.parseInt(ips[i], 16);
            }
            // 用来存储网络唤醒数据包
            byte[] bys = new byte[6 + 16 * macByte.length];
            for (int i = 0; i < 6; i++) {
    
                bys[i] = (byte) 0xff;
            }
            for (int i = 6; i < bys.length; i += macByte.length) {
                System.arraycopy(macByte, 0, bys, i, macByte.length);
            }
            // 将字符形式的 IP 地址转换成标准的 IP 地址
            InetAddress address = InetAddress.getByName("192.168.100.255");
    

    // InetAddress address = InetAddress.getByName("255.255.255.255"); // 生成标准的数据报 DatagramPacket pack = new DatagramPacket(bys, bys.length, address, port); // 创建标准套接字,用来发送数据报 DatagramSocket socket = new DatagramSocket(); // 发送魔法包 socket.send(pack); socket.close(); } catch (Exception e) { e.printStackTrace(); } catch (Throwable e) { e.printStackTrace(); } } }

    5 条回复    2024-04-09 14:17:57 +08:00
    tmtstudio
        1
    tmtstudio  
       255 天前
    用 GPT 啊

    #import <Foundation/Foundation.h>
    #import "GCDAsyncUdpSocket.h"

    @interface TestStr : NSObject
    + (void)wakeup;
    @end

    @implementation TestStr

    + (void)wakeup {
    NSString *mac = @"00:30:64:69:F8:A7"; // mac 地址

    int port = 9;
    NSArray *macComponents = [mac componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":-"]];
    NSMutableData *macData = [NSMutableData data];

    for (NSString *component in macComponents) {
    unsigned char byte;
    [[NSScanner scannerWithString:component] scanHexInt:(unsigned int *)&byte];
    [macData appendBytes:&byte length:1];
    }

    // 用来存储网络唤醒数据包
    NSMutableData *wakeupData = [NSMutableData dataWithLength:6 + 16 * macData.length];
    memset([wakeupData mutableBytes], 0xff, 6);

    for (int i = 6; i < wakeupData.length; i += macData.length) {
    [macData getBytes:[wakeupData mutableBytes] + i length:macData.length];
    }

    // 创建 UDP 套接字
    GCDAsyncUdpSocket *udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:nil delegateQueue:dispatch_get_main_queue()];

    // 将字符形式的 IP 地址转换成标准的 IP 地址
    NSData *addressData = [@"192.168.100.255" dataUsingEncoding:NSUTF8StringEncoding];
    // NSData *addressData = [@"255.255.255.255" dataUsingEncoding:NSUTF8StringEncoding];

    // 发送魔法包
    [udpSocket sendData:wakeupData toHost:[GCDAsyncUdpSocket hostFromAddress:addressData] port:port withTimeout:-1 tag:0];

    [udpSocket close];
    }

    @end

    int main(int argc, const char * argv[]) {
    @autoreleasepool {
    [TestStr wakeup];
    }
    return 0;
    }
    simplove
        2
    simplove  
       255 天前
    以下是将给定的 Java 代码转换为 iOS 使用 GCDAsyncSocket 库的 Swift 代码:
    import Foundation
    import CocoaAsyncSocket

    func wakeup() {
    let mac = "00:30:64:69:F8:A7"
    // let mac = "00:02:a0:01:26:84"

    let port: UInt16 = 9
    let ips = mac.split(separator: ":").map { String($0) }
    var macBytes = [UInt8]()

    for ip in ips {
    if let byte = UInt8(ip, radix: 16) {
    macBytes.append(byte)
    }
    }

    var bys = [UInt8](repeating: 0xff, count: 6 + 16 * macBytes.count)

    for i in 6..<bys.count where i % macBytes.count == 0 {
    bys.replaceSubrange(i..<i+macBytes.count, with: macBytes)
    }

    guard let address = InetAddress("192.168.100.255") else {
    print("Invalid IP address")
    return
    }

    let socket = GCDAsyncUdpSocket(delegate: nil, delegateQueue: DispatchQueue.main)

    do {
    let pack = GCDAsyncUdpSendPacket(data: Data(bys), address: address.host, port: port, timeout: -1)
    try socket?.send(pack, withTimeout: -1)
    } catch let error {
    print("Error: \(error.localizedDescription)")
    }

    socket?.close()
    }

    // You can call wakeup() function from where you need to wake up the device.
    请注意,此代码使用了 CocoaAsyncSocket 库,你需要确保在你的 iOS 项目中添加了该库。
    PbCopy111
        3
    PbCopy111  
       255 天前
    这个是智谱的答案,跟 gpt 一样么?

    iOS 项目使用的第三方 socket 库是`GCDAsyncSocket`。以下是您提供的 Java 代码的 iOS 版本,使用了`GCDAsyncSocket`库。请注意,您需要确保已经将`GCDAsyncSocket`库添加到您的 iOS 项目中。
    ```objective-c
    #import <Foundation/Foundation.h>
    #import <GCDAsyncSocket/GCDAsyncSocket.h>
    @interface teststr : NSObject
    @end
    @implementation teststr
    - (void)wakeup {
    NSString *macAddress = @"00:30:64:69:F8:A7"; // mac 地址
    // 省略了初始化代码...

    int port = 9;
    NSData *macData = [NSData dataWithBytes:macAddress.bytes length:macAddress.length];
    NSMutableData *bys = [NSMutableData dataWithLength:6 + 16 * macData.length];
    for (int i = 0; i < 6; i++) {
    [bys setData:[NSData dataWithBytes:&0xff length:1] atIndex:i];
    }
    for (int i = 6; i < bys.length; i += macData.length) {
    [bys insertData:macData atIndex:i];
    }

    // 将字符形式的 IP 地址转换成标准的 IP 地址
    NSString *ipAddress = @"192.168.100.255";
    NSData *addressData = [ipAddress dataUsingEncoding:NSUTF8StringEncoding];
    NSData *address = [NSData dataWithBytes:addressData.bytes length:addressData.length];

    GCDAsyncUdpSocket *socket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    [socket setDelegateQueue:dispatch_get_main_queue()];
    [socket bindToAddress:address onPort:port error:nil];
    [socket setReuseAddress:YES];
    [socket setEnableBroadcast:YES];
    [socket sendData:bys toHost:address onPort:port withTimeout:0 tag:0];
    [socket close];
    }
    @end
    ```
    在这个 iOS 版本中,我们使用了`GCDAsyncUdpSocket`来发送 UDP 数据报。请确保你的`GCDAsyncSocket`库已经正确集成到项目中,并且已经添加了所有必要的引用。此外,这段代码应该在主线程中运行,因为它涉及到 UI 操作。
    Joky
        4
    Joky  
       255 天前
    ```swift
    import Foundation
    import CocoaAsyncSocket

    class WakeOnLan: NSObject, GCDAsyncUdpSocketDelegate {
    var udpSocket: GCDAsyncUdpSocket!

    override init() {
    super.init()
    udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
    }

    func wakeup(macStr: String, ipStr: String, port: UInt16) {
    let macBytes = macStr.split(separator: ":").compactMap { UInt8($0, radix: 16) }
    guard macBytes.count == 6 else { return }

    var packet = Data(repeating: 0xFF, count: 6)
    for _ in 0..<16 {
    packet.append(contentsOf: macBytes)
    }

    do {
    try udpSocket.enableBroadcast(true)
    udpSocket.send(packet, toHost: ipStr, port: port, withTimeout: -1, tag: 0)
    } catch {
    print("发送数据包时出现了问题: \(error)")
    }
    }

    // GCDAsyncUdpSocketDelegate methods
    func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
    print("数据包发送成功")
    sock.close() // 发送完毕后关闭套接字
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
    if let error = error {
    print("未能发送数据包, 错误: \(error)")
    }
    sock.close() // 如果发送失败,也关闭套接字
    }

    func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
    if let error = error {
    print("UDP socket 已关闭, 错误: \(error)")
    } else {
    print("UDP socket 已正常关闭")
    }
    }
    }

    // 使用
    let wol = WakeOnLan()
    wol.wakeup(macStr: "00:30:64:69:F8:A7", ipStr: "192.168.100.255", port: 9)
    ```
    geniusmary
        5
    geniusmary  
       255 天前
    看楼上代码感觉问题不大 记得 podfile 里添加完库后记得 pod update 或者 install 不然拉不到库代码
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2841 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 11:16 · PVG 19:16 · LAX 03:16 · JFK 06:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.