Sto sviluppando un'applicazione Android che utilizza TCP per la connessione del dispositivo. Il problema è che sono nuovo nella programmazione dei socket. Ho creato con successo un codice server e client. Ogni client può connettersi al server e il server può rispondere al client. Ma non riesco a fare in modo che il server invii un messaggio a tutti i client connessi allo stesso tempo. Quali sono i passaggi per far sì che il server trasmetta un messaggio al client? Questo è il codice del server:Trasmissione server TCP Android
ServerSocket server = null;
try {
server = new ServerSocket(9092); // start listening on the port
} catch (IOException e) {
Log.d("btnCreate onClick", "Could not listen on port: 9092");
}
Socket client = null;
while(true) {
try {
client = server.accept();
} catch (IOException e) {
Log.d("btnCreate onClick", "Accept Failed");
}
//start a new thread to handle this client
Thread t = new Thread(new ClientConn(client));
t.start();
}
E il thread del server:
class ClientConn implements Runnable {
private Socket client;
ClientConn(Socket client) {
this.client = client;
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
/* obtain an input stream to this client ... */
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
/* ... and an output stream to the same client */
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
return;
}
String msg;
try {
while ((msg = in.readLine()) != null) {
Log.d("ClientConn", "Client says: " + msg);
out.println(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Puoi spiegare cosa intendi per "trasmissione" nel tuo contesto? TCP non ha trasmesso. –
Modificato la mia domanda. Vorrei che il server inviasse un messaggio a tutti i client connessi. Non si chiama trasmissione? Sono nuovo nella programmazione dei socket. –