I'm developing an Android application which uses TCP for device connection. The problem is I'm new to socket programming. I've successfully made a server and client code. Each client can connect to the server and server can reply to the client. But I can't seem to make the server to send message to all connected client at the same time. What are the steps to make the server broadcast a message to client? This is the server code:
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();
}
And the server thread:
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();
}
}
}
TCP is a point-to-point connection protocol. This means that when you send a message on a socket, it only goes to one receiver. Other IP protocols such as UDP do have a "broadcast" mode, where one packet can go to multiple receivers, but there is no such thing for TCP.
To have your server send the same message to all clients, the server would have to send one message on each socket for each client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With