下面列出了怎么用com.esotericsoftware.kryonet.Connection的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
}
@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);
}
@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);
}
}
}
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));
}
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));
}
}
}
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);
}
});
}
}
/** 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;
}
/** 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;
}
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);
}
});
}
}
/** 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;
}
@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);
}
}
@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);
}
}
@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));
}
}
@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;
}
}
}
public void sendHosts() {
ConnectMessage message = new ConnectMessage();
for(Connection connection : server.getConnections()) {
message.insertNewHost(connection
.getRemoteAddressTCP().getHostName());
}
server.sendToAllTCP(message);
}
@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();
}
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");
}
}
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);
}
/** 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.");
}
/** 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);
}
/** 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);
}
public void idle (Connection connection) {
if (!started) {
started = true;
start();
}
Object object = next();
if (object == null)
connection.removeListener(this);
else
connection.sendTCP(object);
}
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());
}
@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);
}
}
/** 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.");
}
/** 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);
}
/** 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);
}
public void idle (Connection connection) {
if (!started) {
started = true;
start();
}
Object object = next();
if (object == null)
connection.removeListener(this);
else
connection.sendTCP(object);
}
@Override
public void connected(Connection connection) {
}
@Override
public void disconnected(Connection connection){
disconnected = true;
}