如何在SSID

时间:2016-03-13 19:53:37

标签: android sockets wifimanager

我想通过Wi-Fi打开连接。我目前的代码是:

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返回true,表示操作成功。我不知道下一步该做什么。

我的目标是打开一个套接字,我可以通过刚刚连接的网络进行自定义I / O.如何使用此网络打开套接字?另外,我如何确保我实际连接到网络(我可以设置BroadcastReceiver)?

任何链接或文档都很棒,我不确定在线搜索

1 个答案:

答案 0 :(得分:3)

您必须在第一台设备上使用您喜欢的任何端口运行服务器,我在此示例中尝试使用9000:

try {
    log("Waiting for client...");

    ServerSocket serverSocket = new ServerSocket(9000);
    socket = serverSocket.accept();

    log("A new client Connected!");
} catch (IOException e) {}

然后在端口9000上的另一台设备上搜索此服务器。在此示例中将是:

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) {}
}

如果您有服务器IP,则不需要循环。 对于简单的聊天,我们必须打开一个输入流和输出流:

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) {}
}

并发送消息:

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

对于文件I / O使用相同的方式。