是否可以在 Android 手机上启用 WiFi 网络共享/热点,并通过两个不同的应用程序将其配置为服务器和客户端?
问问题
1252 次
1 回答
1
您不需要两个不同的应用程序。在一个应用程序中集成两个功能。
用于java.net.Socket
客户端实现和java.net.ServerSocket
服务器端实现。
服务器端代码:
调用以启动服务器在端口9809startServer()
处侦听数据(根据需要放置)。
void startServer() throws IOException {
new Thread(() -> {
try {
serverSocket = new ServerSocket(9809);
} catch (IOException e) {
e.printStackTrace();
}
Socket socket = null;
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
DataInputStream stream = null;
try {
if (socket != null) {
stream = new DataInputStream(socket.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
String gotdata = null;
try {
if (stream != null) {
gotdata = stream.readUTF();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
assert socket != null;
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("THE DATA WE HAVE GOT :"+gotdata)
}).start();
客户端代码: 在这里,您应该将充当服务器的设备的 IP 地址放在第 6 行(对于我来说,它是 192.168.1.100)。
调用sendData()
以将数据发送到充当服务器的设备。
void sendData() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket socket = new Socket("192.168.1.100", 9809);
DataOutputStream stream = new DataOutputStream(socket.getOutputStream());
stream.writeUTF("Some data here");
stream.flush();
stream.close();
socket.close();
runOnUiThread(new Runnable() {
@Override
public void run() {
System.out.println("Done!");
}
});
} catch (Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
System.out.println("Fail!");
}
});
e.printStackTrace();
}
}
}).start();
}
于 2017-07-11T17:08:17.997 回答