com.josue.tiled2.client.network.WSNetworkClient.java Source code

Java tutorial

Introduction

Here is the source code for com.josue.tiled2.client.network.WSNetworkClient.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.josue.tiled2.client.network;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.josue.shared.online.NetworkConnection;
import com.josue.shared.online.NetworkMessage;
import com.josue.shared.online.NetworkPackage;
import com.josue.shared.online.NetworkPlayer;
import com.josue.shared.online.NetworkWorld;
import com.josue.tiled2.client.EventBus;
import com.josue.tiled2.client.Subscribe;
import com.josue.tiled2.client.player.GamePlayer;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;
import java.net.URISyntaxException;

@ClientEndpoint
public class WSNetworkClient implements NetworkClient {

    private boolean connected;

    private final ObjectMapper mapper;

    private Session userSession = null;
    private final WebSocketContainer container;
    private URI endpointURI;

    public WSNetworkClient(String host, int port, String map) {
        this.container = ContainerProvider.getWebSocketContainer();
        String url = "ws://" + host + ":" + port + "/game/" + map;
        try {
            endpointURI = new URI(url);
        } catch (URISyntaxException ex) {
            System.err.println(":: NETWORK ERROR, MALFORMED URI SYNTAX: " + url + " ::");
        }

        mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        mapper.setSerializationInclusion(Include.NON_NULL);

    }

    @OnOpen
    public void onOpen(final Session userSession) {
        this.userSession = userSession;
    }

    @OnClose
    public void onClose(final Session userSession, final CloseReason reason) {
        this.userSession = null;
    }

    @OnMessage
    public void onMessage(final String message) {
        System.out.println(":: CLIENT MESSAGE: " + message + " ::");
        try {
            NetworkPackage networkPackage = mapper.readValue(message, NetworkPackage.class);
            switch (networkPackage.getType()) {
            case CONNECTION:
                EventBus.fire(new NetworkClient.NetworkConnectionEvent((NetworkConnection) networkPackage));
                break;
            case PLAYER:
                EventBus.fire(new NetworkClient.NetworkPlayerEvent((NetworkPlayer) networkPackage));
                break;
            case WORLD:
                EventBus.fire(new NetworkClient.NetworkWorldEvent((NetworkWorld) networkPackage));
                break;
            case MESSAGE:
                EventBus.fire(new NetworkClient.NetworkMessageEvent((NetworkMessage) networkPackage));
                break;
            }

        } catch (Exception ex) {
            System.err.println(":: SERIALIZATION ERROR, CAUSE: " + ex.getMessage() + " ::");
        }
    }

    @Override
    public boolean connect(GamePlayer player) {
        try {
            if (connected) {
                return false;
            }
            //connect
            container.connectToServer(this, endpointURI);
            //send inital connection package
            NetworkConnection networkConnection = new NetworkConnection(
                    NetworkConnection.ConnectionState.CONNECTED_PLAYER, player.toOnlinePackage());
            sendMessage(networkConnection);
            connected = true;

            return true;
        } catch (Exception ex) {
            System.err.println(":: NETWORK ERROR, CANNOT CONNECT, CAUSE: " + ex.getMessage() + " ::");
        }
        return false;
    }

    @Override
    public void disconnect(GamePlayer player) {
        try {
            sendMessage(new NetworkConnection(NetworkConnection.ConnectionState.DISCONNECTED,
                    player.toOnlinePackage()));
            userSession.close();
            connected = false;
        } catch (Exception ex) {
            System.err.println(":: NETWORK ERROR WHILE DISCONNECTING, CAUSE: " + ex.getMessage() + " ::");
        }
    }

    @Override
    public void sendMessage(NetworkPackage message) {
        try {
            String jsonPayload = mapper.writeValueAsString(message);
            userSession.getAsyncRemote().sendText(jsonPayload); //send async
        } catch (Exception ex) {
            System.err.println(":: NETWORK ERROR WHILE SENDING MESSAGE, CAUSE: " + ex.getMessage() + " ::");
        }
    }

    @Override
    public boolean isConnected() {
        return connected;
    }

    @Subscribe(async = true)
    public void onPlayerWillMove(GamePlayer.PlayerWillMoveEvent move) {
        NetworkPlayer onlinePackage = new NetworkPlayer();
        onlinePackage.setUuid(move.playerUuid);
        onlinePackage.setGlobalPosition(move.future);
        onlinePackage.setCollided(move.colided);
        onlinePackage.setSpeed(move.speed);
        onlinePackage.setAxis(move.axis);
        sendMessage(onlinePackage);
    }

    @Subscribe
    public void onPlayerChat(GamePlayer.PlayerChatEvent chat) {
        NetworkMessage networkMessage = new NetworkMessage();
        networkMessage.setPlayerUuid(chat.playerUuid);
        networkMessage.setMessage(chat.message);
        sendMessage(networkMessage);
    }

}