Search code examples
androidsocketswifi

Android Network Searching


I am creating an app the will require people to connect to each other over WiFi to enable them to play together.

However i don't want to search for a person by IP address i want to search for all the people hosting a game currently and update a list of those people from which i can click on to connect.

Server

public class server extends AppCompatActivity {
int numPlayers=0;
int count = 0;
TextView infoip, msg;
String message = "";
ServerSocket serverSocket;
private String name="server";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_server);
    Bundle b = this.getIntent().getExtras();
    numPlayers = b.getInt("numPlayers");
    //name = b.getString("name");

    infoip = (TextView) findViewById(R.id.serverText);
    msg = (TextView) findViewById(R.id.serverPlayerCount);

    infoip.setText("Hosting...");

    Thread socketServerThread = new Thread(new SocketServerThread());
    socketServerThread.start();
    ButtClickListener();
}
@Override
protected void onDestroy() {
    if (serverSocket != null) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
 }
private void ButtClickListener() {
    Button cancel = (Button) findViewById(R.id.severQuit);
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

private class SocketServerThread extends Thread 

{
static final int SocketServerPORT = 8080;

@Override
public void run() {
    try {
        serverSocket = new ServerSocket(SocketServerPORT);
        server.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
            }
        });

        while (true) {
            Socket socket = serverSocket.accept();
            count++;
            message += "#" + count + " from " + socket.getInetAddress()
                    + ":" + socket.getPort() + "\n";

            server.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    msg.setText(message);
                }
            });

            SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
                    socket, count);
            socketServerReplyThread.run();

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

private class SocketServerReplyThread extends Thread {

private Socket hostThreadSocket;

SocketServerReplyThread(Socket socket, int c) {
    hostThreadSocket = socket;
    count = c;
}

@Override
public void run() {
    OutputStream outputStream;
    String msgReply = "You are the #" + count+" person out of "+count+"/"+numPlayers;

    try {
        outputStream = hostThreadSocket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        printStream.print(msgReply);
        printStream.close();

        message += msgReply + "\n";

        server.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                msg.setText(message);
            }
        });

    } catch (IOException e) {
        e.printStackTrace();
        message += "Error " + e.toString() + "\n";
    }

    server.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            msg.setText(message);
        }
    });
}

}

   private String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += "SiteLocalAddress: "
                            + inetAddress.getHostAddress() + "\n";
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
}
}

Client

public class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Socket socket = new Socket(serverAddr,
                    8080);
            connected = true;
            while (connected) {
                try {
                } catch (Exception e) {
                }
            }
            socket.close();
        } catch (Exception e) {
            connected = false;
        }
    }
}

The above code is to be implemented when i find a server by clicking on it i will be able to connect to the server by the name, but i don't know how to search for the servers.

How would i go about modifying the client side so when it runs it will search for all potential servers and return a list of server names?.

Thanks.


Solution

  • I think this is an excellent usecase for Network Service Discovery http://developer.android.com/training/connect-devices-wirelessly/nsd.html