我在这里给出了代码。我想在iPhone中制作类似的代码。但是不能正确地做到这一点。任何人都可以帮助我。它是服务器发现代码。
尝试过UDP套接字代码但没有得到实际结果。需要让它正常工作我在这里发布代码。
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);
}
}
但是获得以下错误:
接收错误:错误Domain = GCDAsyncUdpSocketErrorDomain Code = 1“必须先绑定套接字才能接收数据。您可以通过bind显式执行此操作,也可以通过connect或发送数据隐式执行此操作。” UserInfo = 0x7f9fc25613a0 {NSLocalizedDescription =必须先绑定套接字才能接收数据。您可以通过bind显式执行此操作,也可以通过connect或通过发送数据隐式执行此操作。}
我不知道这是否是正确的代码。请建议我。