Search in sources :

Example 1 with Client

use of com.esotericsoftware.kryonet.Client in project ProjektGG by eskalon.

the class NetworkHandler method setUpConnectionAsClient.

/**
 * Connects the client to the server. After it is finished a
 * {@link ConnectionEstablishedEvent} is posted on the
 * {@linkplain ProjektGG#getEventBus() event bus}.
 *
 * @param ip
 *            The server's ip.
 * @param port
 *            The server's port.
 */
public void setUpConnectionAsClient(String ip, int port) {
    client = new Client();
    client.start();
    NetworkRegisterer.registerClasses(client.getKryo());
    TypeListener listener = new TypeListener();
    // GAME SETUP MESSAGE (ON CLIENT CONNECT)
    listener.addTypeHandler(GameSetupMessage.class, (con, msg) -> {
        eventBus.post(new GameSessionSetupEvent(msg.getPlayers(), msg.getId(), msg.getSettings()));
        localClientId = msg.getId();
        Gdx.app.log("Client", "Netzwerk ID: " + localClientId);
    });
    // NEW CHAT MESSAGE
    listener.addTypeHandler(ChatMessageSentMessage.class, (con, msg) -> {
        eventBus.post(new NewChatMessagEvent(msg.getSenderId(), msg.getMessage()));
    });
    // PLAYER CHANGED
    listener.addTypeHandler(PlayerChangedMessage.class, (con, msg) -> {
        eventBus.post(new PlayerChangedEvent(msg.getId(), msg.getPlayer()));
    });
    // PLAYER JOINED
    listener.addTypeHandler(PlayerJoinedMessage.class, (con, msg) -> {
        eventBus.post(new PlayerConnectedEvent(msg.getId(), msg.getPlayer()));
    });
    // PLAYER LEFT
    listener.addTypeHandler(PlayerLeftMessage.class, (con, msg) -> {
        eventBus.post(new PlayerDisconnectedEvent(msg.getId()));
    });
    client.addListener(listener);
    Thread t = new Thread(new Runnable() {

        public void run() {
            IOException ex = null;
            try {
                client.connect(6000, ip, port);
                Gdx.app.log("Client", "Lobby beigetreten");
            } catch (IOException e) {
                ex = e;
                e.printStackTrace();
            }
            eventBus.post(new ConnectionEstablishedEvent(ex));
        }
    });
    t.start();
}
Also used : PlayerConnectedEvent(de.gg.event.PlayerConnectedEvent) ConnectionEstablishedEvent(de.gg.event.ConnectionEstablishedEvent) TypeListener(com.esotericsoftware.kryonet.Listener.TypeListener) GameSessionSetupEvent(de.gg.event.GameSessionSetupEvent) NewChatMessagEvent(de.gg.event.NewChatMessagEvent) PlayerChangedEvent(de.gg.event.PlayerChangedEvent) PlayerDisconnectedEvent(de.gg.event.PlayerDisconnectedEvent) IOException(java.io.IOException) Client(com.esotericsoftware.kryonet.Client)

Example 2 with Client

use of com.esotericsoftware.kryonet.Client in project ProjektGG by eskalon.

the class BaseGameClient method connect.

/**
 * Tries to connect the client to the server asynchronously. After it is
 * finished the given listener is called.
 *
 * @param callback
 *            The listener callback.
 * @param gameVersion
 *            the client's game version.
 * @param ip
 *            The server's ip address.
 * @param port
 *            The server's port.
 */
public void connect(ISuccessCallback callback, String gameVersion, String ip, int port) {
    Preconditions.checkNotNull(callback, "callback cannot be null.");
    Preconditions.checkNotNull(gameVersion, "game version cannot be null.");
    Preconditions.checkNotNull(ip, "ip cannot be null.");
    Log.info("Client", "--- Connecting to Server ---");
    client = new Client();
    client.start();
    TypeListener listener = new TypeListener();
    // CLIENT CONNECTION
    // On Server acceptance (stage 1 of connection)
    listener.addTypeHandler(ServerAcceptanceResponse.class, (con, msg) -> {
        client.sendTCP(new ClientHandshakeRequest(MachineIdentificationUtils.getHostname(), gameVersion));
    });
    // Server full
    listener.addTypeHandler(ServerRejectionResponse.class, (con, msg) -> {
        Log.info("Client", "Couldn't connect: Client was rejected (%s)", msg.getMessage());
        callback.onFailure(msg.getMessage());
    });
    // Server handshake (stage 2 of connection)
    listener.addTypeHandler(SuccessfulHandshakeResponse.class, (con, msg) -> {
        Log.info("Client", "Connection established. Local network ID is: %d", localClientId);
        localClientId = msg.getClientNetworkId();
        onSuccessfulHandshake();
        client.addListener(new Listener() {

            @Override
            public void disconnected(Connection connection) {
                Log.info("Client", "Connection closed!");
                onDisconnection();
            }
        });
        callback.onSuccess(null);
    });
    listener.addTypeHandler(FailedHandshakeResponse.class, (con, msg) -> {
        Log.info("Client", "Couldn't connect: Handshake was not successful (%s)", msg.getMsg());
        callback.onFailure(msg.getMsg());
    });
    // Ping
    listener.addTypeHandler(Ping.class, (con, msg) -> {
        if (msg.isReply) {
            this.ping = con.getReturnTripTime();
            Log.info("Client", "Ping: %d", ping);
        }
    });
    onCreation();
    client.addListener(listener);
    ThreadHandler.getInstance().executeRunnable(() -> {
        try {
            client.connect(6000, ip, port);
        // A successful connection further requires a proper handshake
        } catch (IOException e) {
            Log.error("Client", "Couldn't connect: %s", e);
            callback.onFailure("Couldn't connect: " + e.getMessage());
        }
    });
}
Also used : TypeListener(com.esotericsoftware.kryonet.Listener.TypeListener) Listener(com.esotericsoftware.kryonet.Listener) TypeListener(com.esotericsoftware.kryonet.Listener.TypeListener) Connection(com.esotericsoftware.kryonet.Connection) IOException(java.io.IOException) Client(com.esotericsoftware.kryonet.Client) ClientHandshakeRequest(de.gg.engine.network.message.ClientHandshakeRequest)

Example 3 with Client

use of com.esotericsoftware.kryonet.Client in project ProjektGG by eskalon.

the class ServerDiscoveryHandler method discoverHosts.

/**
 * @param port
 *            The port to listen on.
 * @param listener
 *            The listener that is informed when a server is found.
 */
public void discoverHosts(int port, HostDiscoveryListener<P> listener) {
    Preconditions.checkArgument(port > 0, "the port must be valid");
    Preconditions.checkNotNull(listener, "the listener cannot be null");
    Client c = new Client();
    c.getKryo().register(packetClass);
    c.setDiscoveryHandler(new ClientDiscoveryHandler() {

        @Override
        public DatagramPacket onRequestNewDatagramPacket() {
            byte[] buffer = new byte[1024];
            return new DatagramPacket(buffer, buffer.length);
        }

        @Override
        public void onDiscoveredHost(DatagramPacket datagramPacket) {
            Object obj = c.getKryo().readClassAndObject(new Input(datagramPacket.getData()));
            if (packetClass.isInstance(obj))
                listener.onHostDiscovered(datagramPacket.getAddress().getHostAddress(), packetClass.cast(obj));
        }

        @Override
        public void onFinally() {
        }
    });
    c.discoverHosts(port, timeout);
    c.close();
}
Also used : Input(com.esotericsoftware.kryo.io.Input) DatagramPacket(java.net.DatagramPacket) Client(com.esotericsoftware.kryonet.Client) ClientDiscoveryHandler(com.esotericsoftware.kryonet.ClientDiscoveryHandler)

Aggregations

Client (com.esotericsoftware.kryonet.Client)3 TypeListener (com.esotericsoftware.kryonet.Listener.TypeListener)2 IOException (java.io.IOException)2 Input (com.esotericsoftware.kryo.io.Input)1 ClientDiscoveryHandler (com.esotericsoftware.kryonet.ClientDiscoveryHandler)1 Connection (com.esotericsoftware.kryonet.Connection)1 Listener (com.esotericsoftware.kryonet.Listener)1 ClientHandshakeRequest (de.gg.engine.network.message.ClientHandshakeRequest)1 ConnectionEstablishedEvent (de.gg.event.ConnectionEstablishedEvent)1 GameSessionSetupEvent (de.gg.event.GameSessionSetupEvent)1 NewChatMessagEvent (de.gg.event.NewChatMessagEvent)1 PlayerChangedEvent (de.gg.event.PlayerChangedEvent)1 PlayerConnectedEvent (de.gg.event.PlayerConnectedEvent)1 PlayerDisconnectedEvent (de.gg.event.PlayerDisconnectedEvent)1 DatagramPacket (java.net.DatagramPacket)1