i'm stuck with this code, and i think that i'm missing something really important.
when the thread is running i can add message to the vector
but when it calls notify it seems that the getNextMessageFromQueue()
keep to stay on the wait.
Am i locking the messages vars?
Thanks for your help.
My dispatcher class which send all messages to my clients :
private Vector<Message> messages = new Vector<Message>();
public synchronized void addMessage(Message message) {
messages.add(message);
notify();
}
private synchronized Message getNextMessageFromQueue() throws InterruptedException {
while (messages.size() < 1) {
wait();
}
Message message = (Message) messages.get(0);
messages.removeElementAt(0);
return message;
}
private void sendMessageToAllClients(Message message) {
for (int i=0; i < clients.size(); i++) {
Client client = (Client) clients.get(i);
client.sendMessage(message);
}
}
public void run() {
try {
while (true) {
Message message = getNextMessageFromQueue();
sendMessageToAllClients(message);
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
Here the client class :
private Socket socket;
private ObjectOutputStream out;
private ObjectInputStream in;
public Client(Socket s) throws IOException {
socket = s;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
}
public Socket getSocket() {
return socket;
}
public void sendMessage(Message message) {
try {
out.writeObject(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the main call of addMessage
:
Message message = new Message();
message.setMessage("Welcome to " + client.getSocket().getLocalAddress() + ":" + client.getSocket().getPort());
dispatcher.addMessage(message);