Skip to content

Instantly share code, notes, and snippets.

@jtuttas
Created September 8, 2014 07:11
Show Gist options
  • Save jtuttas/6a28b3d8e1233fbe6765 to your computer and use it in GitHub Desktop.
Save jtuttas/6a28b3d8e1233fbe6765 to your computer and use it in GitHub Desktop.
public class Client implements Observer{
private String name;
private String pw;
public Client(String user,String pw) {
this.name=user;
this.pw=pw;
}
@Override
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
System.out.println ("Server -> Client "+name+arg1);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "client "+name;
}
public String getName() {
// TODO Auto-generated method stub
return name;
}
public String getPW() {
// TODO Auto-generated method stub
return pw;
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Client c1 = new Client("Thomas","mmbbs");
Client c2= new Client("Frank","mbs");
Client c3= new Client("Simone","mmbbs");
Server s = new Server();
s.addObserver(c1);
s.addObserver(c2);
s.addObserver(c3);
s.sendChat(new Message("","Nun sind alle da"));
s.deleteObserver(c1);
s.sendChat(new Message("","Nun ist einer weg"));
}
}
public class Message {
private String from;
private String msg;
public Message(String from,String msg) {
this.from=from;
this.msg=msg;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return from+":'"+msg+"'";
}
}
public class Server extends Observable{
public void sendChat(Message m) {
// TODO Auto-generated method stub
setChanged();
notifyObservers(m);
}
public synchronized void addObserver(Client c) {
// TODO Auto-generated method stub
if (c.getPW().compareTo("mmbbs")==0) {
super.addObserver(c);
this.sendChat(new Message("",c.getName()+" has joinded"));
}
else {
c.update(this, new Message("","Login failed!"));
}
}
public synchronized void deleteObserver(Client o) {
// TODO Auto-generated method stub
super.deleteObserver(o);
this.sendChat(new Message("",o.getName()+" diconnected"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment