You can have devices communicate point-to-point, no problem. Just keep in mind that: there must be a device that will be treated as a server, that is, who will be listening to a direct connection.
And the second device is the client, IE, who will connect to the server.
Note: Build the Server socket and socket client in threads to not lock the device ui.
Rudimentary code of how the socket could be:
Client Side
try {
String SERVER_SOCKET = "127.0.0.1";
int SERVER_PORT = 8989;
Socket socket = new Socket(SERVER_SOCKET, SERVER_PORT);
String inputLine;
BufferedReader in = new BufferedReader( InputStreamReader(socket.getInputStream()) );
while( (inputLine = in.readLine()) != null ){
Log.d("socketcst", "Recebendo dados do servidor" );
Log.d("socketcst", inputLine );
}
Log.d("socketcst", "Connectou ao servidor");
} catch (UnknownHostException e) {
Log.d("socketcst", "UnknownHostException: " + e.toString());
} catch (IOException e) {
Log.d("socketcst", "IOException: " + e.toString());
} finally {
if (socket != null) {
try {
socket.close();
Log.d("socketcst", "Fechou a conexão com o servidor");
} catch (IOException e) {
Log.d("socketcst", "IOException - Close: " + e.toString());
}
}
}
Server Side
private String host = "192.168.0.31";
private int port = 8989;
private int conexoes = 50;
Socket socket = new Socket(this.port, this.conexoes);
InetAddress inet = socket.getInetAddress();
System.out.println("Servidor iniciado na porta " + this.port );
while (!socket.isClosed()) {
socket.accept();
try {
InputStreamReader entrada = new InputStreamReader(socket.getInputStream());
OutputStreamWriter saida = new OutputStreamWriter(socket.getOutputStream());
PrintWriter os = new PrintWriter(saida);
String inputLine;
BufferedReader in = new BufferedReader( entrada );
JSONObject dadosEntrada = null;
while ((inputLine = in.readLine()) != null) {
Log.d("socketcst", inputLine );
}
} catch (IOException e) {
System.out.println( e.getMessage() );
}
}
socket.close();
All code must be run as services or threads to not block the application.
Thank you Mauricio, for clarifying this doubt. I will do this.
– Emerson Barcellos
Even a few days ago I did something of this kind
– Mauricio Wanderley Martins
Then I use the IP of each device?
– Emerson Barcellos
It will only import the IP and the server socket port, in the case of the current IP of the mobile phone that will be the Server and the port that it will provide for connection. Client must connect to IP and server socket specific port
– Mauricio Wanderley Martins
I believe whatever he wants to create is like a P2P transmission between the devices. In addition, it could have a code snippet explaining the operation.
– Grupo CDS Informática