Search code examples
androidsocketswifimanager

How to open socket over wifi given an SSID


I want to open a connection over Wi-Fi. My current code is:

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", "MY_SSID");
wifiConfig.preSharedKey = String.format("\"%s\"", "MY_PASSWORD");

int netId = wifiManager.addNetwork(wifiConfig);
if (netId != -1 ) {
     wifiManager.enableNetwork(netId, true);
}

enableNetwork returns true which means the operation is successful. I'm not sure what to do next though.

My goal is to open a socket where I can do custom I/O over the network I have just connected to. How can I open a socket with this network? Also, how can I make sure that I actually connected to the network (is there a BroadcastReceiver I can setup)?

Any links or documentation would be awesome, I'm not sure what to search online


Solution

  • You must run a server on first device with any port you like, I'm trying 9000 in this example:

    try {
        log("Waiting for client...");
    
        ServerSocket serverSocket = new ServerSocket(9000);
        socket = serverSocket.accept();
    
        log("A new client Connected!");
    } catch (IOException e) {}
    

    then search for this server on the other device on port 9000. in this example would be:

    for (int i = 1; i <= 255; i++) {
        String ip = range + i;
        try {
            log("Try IP: " + ip);
            socket = new Socket();
            socket.connect(new InetSocketAddress(ip, 9000), 10);
    
            log("Connected!");
            return true;
        } catch (Exception e) {}
    }
    

    if you have the server ip you don't need loop. and for a simple chat you we must open an inputstream and outputstream like this:

    try {
        outputStream = new DataOutputStream(socket.getOutputStream());
        inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (IOException e1) {
        log("Error: Connection is not stable, exit");
        shutdown();
    }
    
    while (true) {
        try {
            String message = inputStream.readLine();
            if (message != null) {
                log(message);
            }
        } catch (IOException e) {}
    }
    

    and send message with:

    try {
        String message = input.getText().toString() + "\n";
        outputStream.write(message.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    for file I/O use the same way.