i found this post. "Guice newbie question: creating N objects on-
demand"
this work. but this is a good aproach ?.
public class ServerTCP implements ServerInterface {
private final DispatchHandler.Factory handlerFactory;
@Inject ServerTCP(DispatchHandler.Factory handlerFactory) { ... }
@Override
public void start() {
try {
ServerSocket serverSocket = new ServerSocket(4000);
//<-- @Named
("port") int port ?.
while(true){
Socket socket = serverSocket.accept();
handlerFactory.newInstance(socket).start();
}
} catch (IOException e) { e.printStackTrace(); }
}
}
public class DispatchHandler extends Thread {
private Socket socket;
private DispatchHandler(Socket socket) {
this.socket = socket;
}
public static class Factory {
public DispatchHandler newInstance(Socket socket) {
return new DispatchHandler(socket);
}
}
public void run() { /*TODO...*/ }
}
On 20 mar, 12:04, ale <[email protected]> wrote:
> hello,
>
> how can I wrap a socket with guice?
> For example:
> I have an application that receives information via TCP or UDP or TCP/
> HTTP.
>
> I want to inject an implementation without having to modify my code.
>
> example:
>
> public class SocketConnectionProvider implements Provider<Class> {
> private ServerSocket server;
> @Inject public SocketProvider(ServerSocket server){
> this.server = server;
> }
> @Override public ServerConnection get() {
> //This is ok, here ?
> return new TCPServerConnection(server.accept());
> }
>
> }
>
> public class DatagramConnectionProvider implements Provider<Class> {
> private DatagramSocket server;
> public SocketProvider(ServerSocket server){
> this.server = server;
> }
> @Override public ServerConnection get() {
> //This is ok, here ?
> DatagramPacket receivePacket = new DatagramPacket(new
> byte[1024],
> 1024);
> socket.receive(receivePacket);
> return new UDPServerConnection(receivePacket);
> }
>
> }
>
> public void configure() {
> bind(FrontServer.class).to(FrontTCPServer.class);
> bind(FrontConnection.class).to(SocketConnectionProvider.class);
> //bind(FrontConnection.class).to(DatagramConnectionProvider.class);
>
> }
>
> @Inject
> public Foo(FrontServer frontServer) {
> frontServer.start();
>
> }
>
> public class FrontTCPServer extends FrontAbstractServer {
> Provider<SocketConnectionProvider> provider;
> public void start() {
> while(true) {
> ServerConnection serverConnection = provider.get();
> super.handleConnection(serverConnection);
> }
> }
>
> }
>
> public class FrontUDPServer {
>
> }
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-guice?hl=en
-~----------~----~----~----~------~----~------~--~---