/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
import enums.ServiceTags;
import framework.IATMCModel;
import framework.IPlaneDataObject;
import framework.IPlaneUpdateObject;
import framework.IReceive;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import messages.ServiceObject;
/**
*
* @author m0ng
*/
public class Receive extends Thread implements IReceive {
private Socket clientSocket;
private IATMCModel model;
private ObjectInputStream in;
private Object input;
private ServiceObject so;
private boolean running;
public Receive(Socket clientSocket, IATMCModel model) {
startReceiver(clientSocket, model);
this.setDaemon(true);
}
public boolean startReceiver(Socket clientSocket, IATMCModel model) {
this.clientSocket = clientSocket;
this.model = model;
try {
in = new ObjectInputStream(clientSocket.getInputStream());
running=true;
start();
return true;
} catch (IOException ex) {
closeConnection();
Logger.getLogger(Receive.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
public void handleObjects(Object o) {
if (o instanceof ServiceObject) {
so = (ServiceObject) o;
if (so.isTag(ServiceTags.NameAlreadyExists)) {
model.getClient().addStatusMessage("Your NickName is already in use!");
closeConnection();
} else if (so.isTag(ServiceTags.FunctionList)) {
model.setFunctions(so.getFunctions());
}else if (so.isTag(ServiceTags.UserList)) {
model.getClient().setUserList(so.getUserList());
}else if (so.isTag(ServiceTags.chatMessage)) {
model.getClient().addChatMessage(so.getSenderName()+":"+so.getValue());
}
} else if(o instanceof IPlaneUpdateObject){
IPlaneUpdateObject puo = (IPlaneUpdateObject)o;
model.addPlaneUpdate(puo);
} else if(o instanceof IPlaneDataObject){
IPlaneDataObject pdo = (IPlaneDataObject)o;
model.addPlaneData(pdo);
}
}
public void closeConnection() {
running=false;
this.interrupt();
try {
in.close();
model.getClient().setFunctionChooser(false);
model.disconnect();
} catch (IOException ex) {
Logger.getLogger(Receive.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run() {
while (model.isConnected() && running) {
try {
input = in.readObject();
handleObjects(input);
} catch (IOException ex) {
closeConnection();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Receive.class.getName()).log(Level.SEVERE, null, ex);
} catch (ArrayStoreException ex){
Logger.getLogger(Receive.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}