1

我在这里给出代码。我正在尝试在 iPhone 中制作类似的代码。但不能正确地做到这一点。任何人都可以帮助我。它是服务器发现代码。

也尝试过使用 UDP Socket 代码,但没有得到实际结果。需要让它正常工作,就像我在这里发布代码一样。

public class DiscoverServer {
    public static String SERVER_IP;
    private static final int RETRY = 10;
    private static int retryCount = 0;

    public static boolean isServerIPAvailable() {
        retryCount = 0;
        return discoverServer();
    }

    private static boolean discoverServer() {
            DatagramSocket c = null;
            retryCount++;

            if(retryCount == RETRY){
                return false;
            }

            // Find the server using UDP broadcast
            try {
                //Open a random port to send the package
                c = new DatagramSocket();
                c.setBroadcast(true);

                byte[] sendData = "MESSAGE".getBytes();

                //Try the 255.255.255.255 first
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8139);
                    c.send(sendPacket);
                    Log.i("DEBUG", "Discovery Message Broadcased to: 255.255.255.255 (Default)");
                } catch (Exception e) {
                }

                // Broadcast the message over all the network interfaces
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface networkInterface = interfaces.nextElement();

                    if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                        continue; // Don't want to broadcast to the loopback interface
                    }

                    for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                        InetAddress broadcast = interfaceAddress.getBroadcast();
                        if (broadcast == null) {
                            continue;
                        }

                        // Send the broadcast package!
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8139);
                            c.send(sendPacket);
                        } catch (Exception e) {
                        }

                        Log.i("DEBUG", "Discovery Message Broadcased to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
                    }
                }

                Log.i("DEBUG", "Discovery Message Broadcased over all network interfaces. Now waiting for a reply!");

                //Wait for a response
                byte[] recvBuf = new byte[15000];
                DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
                c.setSoTimeout(10000);
                try {
                    c.receive(receivePacket);                
                } catch(SocketTimeoutException e) {
                    discoverServer();
                }

                //Check if the message is correct
                String message = new String(receivePacket.getData()).trim();
                if (message.equals("MESSAGE")) {
                    SERVER_IP = receivePacket.getAddress().getHostAddress();
                    Log.i("DEBUG", "Found Server at " + SERVER_IP);
                    return true;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                //Close the port!
                if(c != null) {
                    c.close();                
                }
            }
            return false;
        }
}

在 iOS 中尝试过以下代码:

#import "ViewController.h"
#import "AppDelegate.h"
#import "GCDAsyncUdpSocket.h"



@interface ViewController ()
{
    AppDelegate *deleg;
    GCDAsyncUdpSocket *udpSocket;
}
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSData *data = [@"MESSAGE" dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:data toHost:@"255.255.255.255" port:1111 withTimeout:-1 tag:1];

    NSError *error = nil;

    if (![udpSocket bindToPort:1111 error:&error])
    {
        NSLog(@"Error binding: %@", [error description]);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", [error description]);
        return;
    }
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if (msg)
    {
        NSLog(@"%@",msg);

    }
    else
    {
        NSString *host = nil;
        uint16_t port = 0;
        [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

        NSLog(@"Unknown Message: %@:%hu", host, port);
    }
}

但出现以下错误:

接收错误:错误域 = GCDAsyncUdpSocketErrorDomain 代码 = 1 “必须先绑定套接字,然后才能接收数据。您可以通过绑定显式执行此操作,或通过连接或发送数据隐式执行此操作。” UserInfo=0x7f9fc25613a0 {NSLocalizedDescription=必须绑定套接字才能接收数据。您可以通过绑定显式执行此操作,或通过连接或发送数据隐式执行此操作。}

我不知道这是否是正确的代码。请给我建议。

4

0 回答 0