Is it possible to enable WiFi tethering/hotspot on an android phone and configure it to be a server as well as client through two different apps?
Asked
Active
Viewed 1,471 times
3
-
you mean client as in Wifi-Client or as in TCP/UDP-Client? – Badmaster Oct 25 '13 at 09:05
-
As in TCP/UDP client... – Nitin Bansal Nov 12 '13 at 08:05
-
Ys, it's possible – Jul 11 '17 at 16:35
1 Answers
1
You don't need two different application. Integrate two functions in one app.
Use java.net.Socket
for client-side implementation and java.net.ServerSocket
for server-side implementation.
Server-Side Code:
Call startServer()
to start server listening for data at port 9809(Put as you wish).
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();
Client-Side Code: Here, You should put the IP address of the device acting as server in line 6(For my case, it was 192.168.1.100).
Call sendData()
to send data to the device acting as server.
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();
}