com.esotericsoftware.kryonet.Connection Java Examples

The following examples show how to use com.esotericsoftware.kryonet.Connection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BenchServer.java    From rpc-bench with Apache License 2.0 6 votes vote down vote up
@Override
public void received(final Connection connection, final Object object) {
  if (object instanceof Size) {
    final Size size = (Size) object;
    final long tod = size.tod;
    final int msgs = size.messages;
    final Price price = new Price();
    for (int i = 0; i < msgs; i++) {
      price.tod = tod;
      price.iid = i;
      price.bid = 2;
      price.ask = 3;
      price.trd = 4;
      price.vol = 5;
      while (!connection.isIdle()) {
        // busy spin waiting for space in buffer
        IDLE.idle();
      }
      connection.sendTCP(price);
    }
  }
}
 
Example #2
Source File: ObjectSpace.java    From RuinsOfRevenge with MIT License 6 votes vote down vote up
/** Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs to. */
static Object getRegisteredObject (Connection connection, int objectID) {
	ObjectSpace[] instances = ObjectSpace.instances;
	for (int i = 0, n = instances.length; i < n; i++) {
		ObjectSpace objectSpace = instances[i];
		// Check if the connection is in this ObjectSpace.
		Connection[] connections = objectSpace.connections;
		for (int j = 0; j < connections.length; j++) {
			if (connections[j] != connection) continue;
			// Find an object with the objectID.
			Object object = objectSpace.idToObject.get(objectID);
			if (object != null) return object;
		}
	}
	return null;
}
 
Example #3
Source File: StateProcessor.java    From killingspree with MIT License 6 votes vote down vote up
@Override
public void received(Connection connection, Object object) {
    if (object instanceof GameStateMessage) {
        addNewState((GameStateMessage) object);
    } else if (object instanceof Short) {
        if(world.get(object) != null ) {
            world.get(object).destroy = true;
            //FIXME Set remove in the client entity
            if (!(world.get(object) instanceof ClientBomb))
                world.get(object).remove = true;
        }
    } else if (object instanceof AudioMessage) {
        audioPlayer.playAudioMessage((AudioMessage) object);
    } else if (object instanceof PlayerNamesMessage) {
        this.playerNames = (PlayerNamesMessage) object;
    } else if (object instanceof ServerStatusMessage) {
        ServerStatusMessage message = (ServerStatusMessage) object;
        toaster.toast(message.toastText);
        disconnected = true;
    } else if (object instanceof String) {
        toaster.toast((String) object);
    }
    super.received(connection, object);
}
 
Example #4
Source File: NetServer.java    From gdx-proto with Apache License 2.0 6 votes vote down vote up
private void handleReceived(Connection conn, Object obj) {
	//AsLog.debug("received from client (" + conn + "): " + obj);
	if (obj instanceof ClientRequest) {
		handleClientRequest(conn, (ClientRequest) obj);
	} else if (obj instanceof ClientUpdate) {
		ClientUpdate clientUpdate = (ClientUpdate) obj;
		ClientInfo clientInfo = clientMap.get(conn);
		clientInfo.lastInputTick = clientUpdate.inputTick;
		handleClientUpdate(clientUpdate);
	} else if (obj instanceof EntityInfoRequest) {
		handleEntityInfoRequest(conn, (EntityInfoRequest) obj);
	} else if (obj instanceof ChatMessage) {
		ChatMessage chat = (ChatMessage) obj;
		chat.playerId = clientMap.get(conn).playerEntityId;
		queueChatMessage((ChatMessage) obj);
	} else {
		if (!obj.getClass().getName().contains("com.esotericsoftware.kryonet")) {
			String err = "unhandled object from client to server: " + obj;
			Log.debug(err);
			queueChatMessage(new ChatMessage(err));
		}
	}
}
 
Example #5
Source File: WorldManager.java    From killingspree with MIT License 6 votes vote down vote up
@Override
        public void received(Connection connection, Object object) {
            try {
                if (object instanceof ControlsMessage) {
                    playerList.get(connection.getID()).
                    setCurrentControls((ControlsMessage) object);
                }
                if (object instanceof ClientDetailsMessage) {
                    updateClientDetails(connection, object);
                }
            }
            catch(Exception e) {
//                if (server != null) {
//                    server.sendToTCP(connection.getID(), "start");
//                }
                ServerPlayer player = new ServerPlayer(id++, playerPositions.get(i).x,
                        playerPositions.get(i).y, worldBodyUtils);
                i++;
                i %= playerPositions.size();
                playerList.put(connection.getID(), player);
                entities.add(player);
                if (object instanceof ClientDetailsMessage) {
                    updateClientDetails(connection, object);
                }
            }
        }
 
Example #6
Source File: ObjectSpace.java    From kryonet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void received (final Connection connection, Object object) {
	if (!(object instanceof InvokeMethod)) return;
	if (connections != null) {
		int i = 0, n = connections.length;
		for (; i < n; i++)
			if (connection == connections[i]) break;
		if (i == n) return; // The InvokeMethod message is not for a connection in this ObjectSpace.
	}
	final InvokeMethod invokeMethod = (InvokeMethod)object;
	final Object target = idToObject.get(invokeMethod.objectID);
	if (target == null) {
		if (WARN) warn("kryonet", "Ignoring remote invocation request for unknown object ID: " + invokeMethod.objectID);
		return;
	}
	if (executor == null)
		invoke(connection, target, invokeMethod);
	else {
		executor.execute(new Runnable() {
			public void run () {
				invoke(connection, target, invokeMethod);
			}
		});
	}
}
 
Example #7
Source File: WorldManager.java    From killingspree with MIT License 6 votes vote down vote up
private void updateClientDetails(Connection connection, Object object) {
    int version = ((ClientDetailsMessage)object).protocolVersion;
    if (version != Constants.PROTOCOL_VERSION) {
        ServerStatusMessage message = new ServerStatusMessage();
        message.status = Status.DISCONNECT;
        if (version > Constants.PROTOCOL_VERSION) {
            message.toastText = "Please update server";
        } else if (version < Constants.PROTOCOL_VERSION) {
            message.toastText = "Please update client";
        }
        server.sendToTCP(connection.getID(), message);
        return;
    }
    
    playerList.get(connection.getID()).
    setName(((ClientDetailsMessage) object).name);
    PlayerNamesMessage players = new PlayerNamesMessage();
    for (ServerPlayer tempPlayer: playerList.values()) {
        players.players.put(tempPlayer.id, tempPlayer.getName());
    }
    if (server != null)
        server.sendToAllTCP(players);
    addOutgoingEvent(MessageObjectPool.instance.eventPool.obtain().
            set(State.RECEIVED, players));
}
 
Example #8
Source File: ObjectSpace.java    From RuinsOfRevenge with MIT License 6 votes vote down vote up
public void received (final Connection connection, Object object) {
	if (!(object instanceof InvokeMethod)) return;
	if (connections != null) {
		int i = 0, n = connections.length;
		for (; i < n; i++)
			if (connection == connections[i]) break;
		if (i == n) return; // The InvokeMethod message is not for a connection in this ObjectSpace.
	}
	final InvokeMethod invokeMethod = (InvokeMethod)object;
	final Object target = idToObject.get(invokeMethod.objectID);
	if (target == null) {
		if (WARN) warn("kryonet", "Ignoring remote invocation request for unknown object ID: " + invokeMethod.objectID);
		return;
	}
	if (executor == null)
		invoke(connection, target, invokeMethod);
	else {
		executor.execute(new Runnable() {
			public void run () {
				invoke(connection, target, invokeMethod);
			}
		});
	}
}
 
Example #9
Source File: ObjectSpace.java    From kryonet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Returns the first ID registered for the specified object with any of the ObjectSpaces the specified connection belongs to,
 * or Integer.MAX_VALUE if not found. */
static int getRegisteredID (Connection connection, Object object) {
	ObjectSpace[] instances = ObjectSpace.instances;
	for (int i = 0, n = instances.length; i < n; i++) {
		ObjectSpace objectSpace = instances[i];
		// Check if the connection is in this ObjectSpace.
		Connection[] connections = objectSpace.connections;
		for (int j = 0; j < connections.length; j++) {
			if (connections[j] != connection) continue;
			// Find an ID with the object.
			int id = objectSpace.objectToID.get(object, Integer.MAX_VALUE);
			if (id != Integer.MAX_VALUE) return id;
		}
	}
	return Integer.MAX_VALUE;
}
 
Example #10
Source File: ObjectSpace.java    From kryonet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs
 * to. */
static Object getRegisteredObject (Connection connection, int objectID) {
	ObjectSpace[] instances = ObjectSpace.instances;
	for (int i = 0, n = instances.length; i < n; i++) {
		ObjectSpace objectSpace = instances[i];
		// Check if the connection is in this ObjectSpace.
		Connection[] connections = objectSpace.connections;
		for (int j = 0; j < connections.length; j++) {
			if (connections[j] != connection) continue;
			// Find an object with the objectID.
			Object object = objectSpace.idToObject.get(objectID);
			if (object != null) return object;
		}
	}
	return null;
}
 
Example #11
Source File: NetServer.java    From gdx-proto with Apache License 2.0 5 votes vote down vote up
public void handleClientRequest(Connection conn, ClientRequest req) {
	ClientInfo info = clientMap.get(conn);
	switch (req) {
		case CreateNewPlayerAssignID:
			DynamicEntity player = createPlayer();
			ServerMessage.AssignPlayerEntityId playerAssignment = new ServerMessage.AssignPlayerEntityId();
			playerAssignment.id = player.id;
			info.playerEntityId = player.id;
			Log.debug("server creating new player, assigning id: " + player.id);
			sendPlayerConnectedChatMessage(player.id);
			playerEntityIds.add(player.id);
			conn.sendTCP(playerAssignment);
			break;
		case RequestServerInfo:
			ServerMessage.ServerInfo serverInfo = new ServerMessage.ServerInfo();
			serverInfo.tickNum = tickNum;
			serverInfo.tickInterval = tickInterval;
			serverInfo.serverName = serverName;
			serverInfo.serverMsg = serverMsg;
			conn.sendTCP(serverInfo);
			break;
		case RequestLevelGeometry:
			ServerMessage.LevelGeometry levelGeometry = new ServerMessage.LevelGeometry();
			levelGeometry.staticPieces = LevelBuilder.staticPieces.toArray(LevelStatic.class);
			conn.sendTCP(levelGeometry);
			break;
		case RequestResetPlayerPosition:
			ClientInfo clientInfo = clientMap.get(conn);
			Log.debug("resetting player position due to client request, id: " + clientInfo.playerEntityId);
			resetPlayerPosition(clientInfo.playerEntityId);
			break;
		default:
			throw new GdxRuntimeException("unhandled");
	}
}
 
Example #12
Source File: TcpIdleSender.java    From RuinsOfRevenge with MIT License 5 votes vote down vote up
public void idle (Connection connection) {
	if (!started) {
		started = true;
		start();
	}
	Object object = next();
	if (object == null)
		connection.removeListener(this);
	else
		connection.sendTCP(object);
}
 
Example #13
Source File: NetServer.java    From gdx-proto with Apache License 2.0 5 votes vote down vote up
public void handleEntityInfoRequest(Connection conn, EntityInfoRequest req) {
	Entity ent = Entity.getEntityById(req.id);
	// TODO in the future put more fields into the response
	EntityInfoRequest.Response resp = new EntityInfoRequest.Response();
	resp.isPlayer = isPlayerEntity(ent.id);
	resp.id = ent.id;
	if (isPlayerEntity(ent.id)) {
		resp.graphicsType = Entity.EntityGraphicsType.Model;
	} else {
		resp.graphicsType = Entity.EntityGraphicsType.Decal;
	}
	conn.sendTCP(resp);
}
 
Example #14
Source File: ObjectSpace.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Causes this ObjectSpace to stop listening to the connections for method invocation messages. */
public void close () {
	Connection[] connections = this.connections;
	for (int i = 0; i < connections.length; i++)
		connections[i].removeListener(invokeListener);

	synchronized (instancesLock) {
		ArrayList<ObjectSpace> temp = new ArrayList(Arrays.asList(instances));
		temp.remove(this);
		instances = temp.toArray(new ObjectSpace[temp.size()]);
	}

	if (TRACE) trace("kryonet", "Closed ObjectSpace.");
}
 
Example #15
Source File: ObjectSpace.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Allows the remote end of the specified connection to access objects registered in this ObjectSpace. */
public void addConnection (Connection connection) {
	if (connection == null) throw new IllegalArgumentException("connection cannot be null.");

	synchronized (connectionsLock) {
		Connection[] newConnections = new Connection[connections.length + 1];
		newConnections[0] = connection;
		System.arraycopy(connections, 0, newConnections, 1, connections.length);
		connections = newConnections;
	}

	connection.addListener(invokeListener);

	if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection);
}
 
Example #16
Source File: ObjectSpace.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Removes the specified connection, it will no longer be able to access objects registered in this ObjectSpace. */
public void removeConnection (Connection connection) {
	if (connection == null) throw new IllegalArgumentException("connection cannot be null.");

	connection.removeListener(invokeListener);

	synchronized (connectionsLock) {
		ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
		temp.remove(connection);
		connections = temp.toArray(new Connection[temp.size()]);
	}

	if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection);
}
 
Example #17
Source File: TcpIdleSender.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void idle (Connection connection) {
	if (!started) {
		started = true;
		start();
	}
	Object object = next();
	if (object == null)
		connection.removeListener(this);
	else
		connection.sendTCP(object);
}
 
Example #18
Source File: RemoteMinecraft.java    From AMIDST with GNU General Public License v3.0 5 votes vote down vote up
public RemoteMinecraft(String address) {
	client = new Client(65536, 65536);
	Kryo kryo = client.getKryo();
	kryo.register(NetCreateWorldRequest.class);
	kryo.register(NetGetBiomeDataRequest.class);
	kryo.register(NetGetBiomeDataResult.class);
	kryo.register(NetBiome.class);
	kryo.register(NetBiome[].class);
	kryo.register(NetInfoRequest.class);
	kryo.register(int[].class);
	
	client.addListener(new Listener() {
		@Override
		public void received(Connection connection, Object object) {
			if (object instanceof NetGetBiomeDataResult) {
				currentResults = (NetGetBiomeDataResult)object;
				//Log.i("Received NetGetBiomeDataResult: " + currentResults);
			} else if (object instanceof NetBiome[]) {
				NetBiome[] biomes = (NetBiome[])object;
				for (int i = 0; i < biomes.length; i++) {
					if (biomes[i] != null) {
						new Biome(biomes[i].name, biomes[i].id, biomes[i].color | 0xFF000000, true);
					}
				}
			}
		}
	});
	
	client.start();
	try {
		client.connect(5000, address, 54580, 54580);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	client.sendTCP(new NetInfoRequest());
	
}
 
Example #19
Source File: ServerConnection.java    From RuinsOfRevenge with MIT License 5 votes vote down vote up
@Override
public void received(Connection connection, Object object) {
	if (object instanceof CreateEntity) {
		CreateEntity create = (CreateEntity) object;
		create.state.id = master.getNewEntityID();
		master.addEntity(create.type, create.state, connection.getID());

		sendToAllTCP(create);
	} else if (object instanceof EntityState) {
		sendToAllUDP((EntityState)object);
	} else if (object instanceof Input) {
		Input in = (Input) object;
		connectedClients.get(connection.getID()).getInput().set(in.time, in);

		sendToTCP(connection, in);
	} else if (object instanceof FetchEntities) {
		ServerEntity[] entities = master.getEntities();
		CreateEntity[] creates = new CreateEntity[entities.length];
		for (int i = 0; i < entities.length; i++) {
			creates[i] = new CreateEntity(master.getTime(), entities[i].getEntity().getType(), entities[i].getEntity());
		}
		sendToTCP(connection, new FetchEntities(master.getTime(), creates));
	} else if (object instanceof ChatMessage) {
		Date date = new Date();
		String msg = String.format("[%s] %s: %s",
				minuteFormat.format(date), connectedClients.get(connection.getID()).getUsername(), object);
		sendToAllTCP(new ChatMessage(msg));
		System.out.println("Chat: " + msg);
	} else {
		System.out.println("Recieved strange object: " + object);
	}
}
 
Example #20
Source File: ObjectSpace.java    From RuinsOfRevenge with MIT License 5 votes vote down vote up
/** Causes this ObjectSpace to stop listening to the connections for method invocation messages. */
public void close () {
	Connection[] connections = this.connections;
	for (int i = 0; i < connections.length; i++)
		connections[i].removeListener(invokeListener);

	synchronized (instancesLock) {
		ArrayList<Connection> temp = new ArrayList(Arrays.asList(instances));
		temp.remove(this);
		instances = temp.toArray(new ObjectSpace[temp.size()]);
	}

	if (TRACE) trace("kryonet", "Closed ObjectSpace.");
}
 
Example #21
Source File: ObjectSpace.java    From RuinsOfRevenge with MIT License 5 votes vote down vote up
/** Allows the remote end of the specified connection to access objects registered in this ObjectSpace. */
public void addConnection (Connection connection) {
	if (connection == null) throw new IllegalArgumentException("connection cannot be null.");

	synchronized (connectionsLock) {
		Connection[] newConnections = new Connection[connections.length + 1];
		newConnections[0] = connection;
		System.arraycopy(connections, 0, newConnections, 1, connections.length);
		connections = newConnections;
	}

	connection.addListener(invokeListener);

	if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection);
}
 
Example #22
Source File: ObjectSpace.java    From RuinsOfRevenge with MIT License 5 votes vote down vote up
/** Removes the specified connection, it will no longer be able to access objects registered in this ObjectSpace. */
public void removeConnection (Connection connection) {
	if (connection == null) throw new IllegalArgumentException("connection cannot be null.");

	connection.removeListener(invokeListener);

	synchronized (connectionsLock) {
		ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
		temp.remove(connection);
		connections = temp.toArray(new Connection[temp.size()]);
	}

	if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection);
}
 
Example #23
Source File: BenchServer.java    From rpc-bench with Apache License 2.0 5 votes vote down vote up
@Override
public void received(final Connection connection, final Object object) {
  if (object instanceof Ping) {
    final Ping ping = (Ping) object;
    final Pong pong = new Pong();
    pong.timestamp = ping.timestamp;
    connection.sendTCP(pong);
  }
}
 
Example #24
Source File: BenchClient.java    From rpc-bench with Apache License 2.0 5 votes vote down vote up
@Override
public void received(final Connection connection, final Object object) {
  if (object instanceof Pong) {
    onPong((Pong) object);
  } else if (object instanceof Price) {
    onPrice((Price) object);
  }
}
 
Example #25
Source File: NetServer.java    From gdx-proto with Apache License 2.0 5 votes vote down vote up
@Override
public void sendUpdateToClients() {
	ServerUpdate serverUpdate = ServerUpdate.createServerUpdate();
	for (Connection client : connectedClients) {
		ClientInfo clientInfo = clientMap.get(client);
		serverUpdate.playerInputTick = clientInfo.lastInputTick;
		client.sendUDP(serverUpdate);
	}
	serverUpdate.free();
}
 
Example #26
Source File: LobbyScreen.java    From killingspree with MIT License 5 votes vote down vote up
public void sendHosts() {
    ConnectMessage message = new ConnectMessage();
    for(Connection connection : server.getConnections()) {
        message.insertNewHost(connection
                .getRemoteAddressTCP().getHostName());
    }
    server.sendToAllTCP(message);
}
 
Example #27
Source File: LobbyScreen.java    From killingspree with MIT License 5 votes vote down vote up
@Override
public void received(Connection connection, Object object) {
    if (object instanceof ConnectMessage) {
        ipAddresses = ((ConnectMessage) object).hosts;
    } else if (object instanceof String) {
        if(((String)object).matches("start")) {
            startGame = true;
        }
    }
}
 
Example #28
Source File: WorldManager.java    From killingspree with MIT License 5 votes vote down vote up
@Override
public void disconnected(Connection connection) {
    ServerPlayer player = playerList.get(connection.getID());
    if (player != null) {
        player.dispose();
        playerList.remove(connection.getID());
        entities.remove(player);
        if (server!= null) {
            server.sendToAllTCP(player.id);
        }
        addOutgoingEvent(MessageObjectPool.instance.
                eventPool.obtain().set(State.RECEIVED, player.id));
    }
}
 
Example #29
Source File: WorldManager.java    From killingspree with MIT License 4 votes vote down vote up
@Override
        public void connected(Connection connection) {
//            if (server != null)
//                server.sendToTCP(connection.getID(), "start");
        }
 
Example #30
Source File: StateProcessor.java    From killingspree with MIT License 4 votes vote down vote up
@Override
public void disconnected(Connection connection){
    disconnected = true;
}