Here i am giving the code. I am trying to make similar code in iPhone. But not able to do it correctly. Can anyone help me for that. It is server discovery code.
Have tried with UDP Socket code also but not getting actual result. Need to get it work correctly as same I am posting code here.
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;
}
}
Have Tried Following Code in 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);
}
}
But Getting Following Error :
Error receiving: Error Domain=GCDAsyncUdpSocketErrorDomain Code=1 "Must bind socket before you can receive data. You can do this explicitly via bind, or implicitly via connect or by sending data." UserInfo=0x7f9fc25613a0 {NSLocalizedDescription=Must bind socket before you can receive data. You can do this explicitly via bind, or implicitly via connect or by sending data.}
I don't know whether this is correct code or not. Please suggest me.