This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/server/src/main/java/envoy/server/net/ObjectWriteProxy.java

89 lines
2.6 KiB
Java
Executable File

package envoy.server.net;
import java.io.IOException;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Stream;
import com.jenkov.nioserver.*;
import envoy.util.*;
import envoy.server.data.Contact;
/**
* This class defines methods to send an object to a client.
*
* @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha
*/
public final class ObjectWriteProxy {
private final WriteProxy writeProxy;
private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
private static final Logger logger =
EnvoyLog.getLogger(ObjectWriteProxy.class);
/**
* Creates an instance of {@link ObjectWriteProxy}.
*
* @param writeProxy the {@link WriteProxy} to write objects to another client
* @since Envoy Server Standalone v0.1-alpha
*/
public ObjectWriteProxy(WriteProxy writeProxy) {
this.writeProxy = writeProxy;
}
/**
* @param recipientSocketID the socket id of the recipient
* @param obj the object to return to the client
* @throws RuntimeException if the serialization of the object failed (this is highly unlikely)
* @since Envoy Server Standalone v0.1-alpha
*/
public void write(long recipientSocketID, Object obj) {
// Create message targeted at the client
final Message response = writeProxy.getMessage();
response.socketId = recipientSocketID;
logger.fine("Sending " + obj);
try {
// Serialize object to byte array
final byte[] objBytes = SerializationUtils.writeToByteArray(obj);
// Acquire object length in bytes
final byte[] objLen = SerializationUtils.intToBytes(objBytes.length);
response.writeToMessage(objLen);
response.writeToMessage(objBytes);
writeProxy.enqueue(response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Sends an object to all contacts in a set that are online.
*
* @param contacts the contacts to send the object to
* @param message the object to send
* @since Envoy Server Standalone v0.1-beta
*/
public void writeToOnlineContacts(Set<? extends Contact> contacts, Object message) {
writeToOnlineContacts(contacts.stream(), message);
}
/**
* Sends an object to all contacts in a set that are online.
*
* @param contacts the contacts to send the object to
* @param message the object to send
* @since Envoy Server Standalone v0.1-beta
*/
public void writeToOnlineContacts(Stream<? extends Contact> contacts, Object message) {
contacts.map(Contact::getID).filter(connectionManager::isOnline)
.map(connectionManager::getSocketID).forEach(id -> write(id, message));
}
}