I am engaging the following problems:
- I need to write a server program, will accept multiple clients
- all clients are subscribing the same data from server, for example the stock price update.
- each clients can send simple commands to server like "logon", "stop"
So here is my solution, Since I am not very experianced in multithread/tcp, I want to know is it a good solution? if not, is there any better solution? is it necessary to have a thread for each client socket? Thanks BTW: sorry for confusing every one, it is a small project that only involve 5-10 classes.
class AcceptThread {
......
public void run () {
ControlThread controlThread = new ControlThread();
controlThread.start();
Socket socket = new Socket(port);
while (!stop) {
Socket s = socket.accept();
controlThread.addClient (s);
}
}
}
class ControlThread {
Set<Scoket> clients;
SendDataThread sendDataThread;
public ControlThread () {
sendDataThread = new SendDataThread();
sendDataThread.start();
}
public void addClient (Socket socket) {
clients.add(socket);
sendDataThread.addListener(socket);
}
public void run () {
......
for (Socket s : clients) {
if (s.getInputStream().available()) {
//read command from s
}
}
......
}
}
class SendDataThread () {
Set<Scoket> listeners;
public void addListener (Socket s) {
listeners.add(s);
}
public void run () {
for (Socket s: listeners) {
// send data to each listener
}
}
}