/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
import enums.ServiceTags;
import framework.IATMCModel;
import framework.IConnection;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import messages.ServiceObject;
/**
*
* @author m0ng85
*/
public class Connection implements IConnection{
private IATMCModel atmcModel;
private Socket clientSocket;
private ObjectOutputStream outStream;
public Connection(IATMCModel model){
atmcModel = model;
}
public boolean connect(String server, int port, String nickName) {
try {
clientSocket = new Socket(server, port);
outStream = new ObjectOutputStream(clientSocket.getOutputStream());
outStream.writeObject(new ServiceObject(nickName, ServiceTags.ClientLoggedIn));
new Receive(clientSocket, atmcModel);
} catch (UnknownHostException ex) {
atmcModel.setStatus("Connection Error: Unknown Host: "+server+":"+port);
outStream = null;
disconnect();
} catch (IOException ex) {
atmcModel.setStatus("Connection Error: IOException: "+server+":"+port);
outStream = null;
disconnect();
} finally {
if(outStream != null){
atmcModel.saveSettings(server, port, nickName);
atmcModel.setStatus("Logged in as "+nickName);
}
return outStream != null;
}
}
public boolean isConnected() {
return outStream != null;
}
public void disconnect() {
try {
if(outStream != null && clientSocket != null){
outStream.close();
clientSocket.close();
}
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
atmcModel.setStatus("Not logged in");
}
public void sendObject(Object o) {
try {
if(outStream != null)outStream.writeObject(o);
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendChatMessage(String message, String to) {
ServiceObject sout = new ServiceObject("name", ServiceTags.chatMessage);
sout.setValue(message);
sendObject(sout);
}
public void keepAlive() {
sendObject(new ServiceObject("name",ServiceTags.KeepAlive));
}
}