package ch.marcsladek.jrtnp.client;
import java.io.IOException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import ch.marcsladek.jrtnp.connection.Connection;
import ch.marcsladek.jrtnp.connection.ConnectionFactory;
public class Client {
protected final Connection server;
/**
*
* @param host
* ip the client connects to
* @param port
* port the client connects to
* @param ssl
* uses Secure Sockets Layer
* @param connectionFactoryClass
* class of the factory used to create objects of own Connection
* implementation
* @throws ReflectiveOperationException
* when unable to use reflection on given class
* @throws IOException
* when error with socket and stream
*/
public Client(String host, int port, boolean ssl,
Class<? extends ConnectionFactory> connectionFactoryClass)
throws ReflectiveOperationException, IOException {
ConnectionFactory factory = connectionFactoryClass.getConstructor().newInstance();
server = factory.newInstance(getSocketFactory(ssl).createSocket(host, port));
}
private SocketFactory getSocketFactory(boolean ssl) {
if (ssl) {
return SSLSocketFactory.getDefault();
} else {
return SocketFactory.getDefault();
}
}
/**
* Starts the listener for the server
*/
public final void start() {
server.start();
}
/**
* Stops the listener for the server
*
* @throws IOException
*/
public final void shutdown() throws IOException {
server.shutdown();
}
@Override
public String toString() {
return server.toString();
}
}