54 lines
1.6 KiB
Java
54 lines
1.6 KiB
Java
package envoy.server.net;
|
|
|
|
import java.io.IOException;
|
|
|
|
import com.jenkov.nioserver.Message;
|
|
import com.jenkov.nioserver.WriteProxy;
|
|
|
|
import envoy.util.SerializationUtils;
|
|
|
|
/**
|
|
* This class defines methods to send an object to a client.<br>
|
|
* <br>
|
|
* Project: <strong>envoy-server-standalone</strong><br>
|
|
* File: <strong>ObjectWriteProxy.java</strong><br>
|
|
* Created: <strong>04.01.2020</strong><br>
|
|
*
|
|
* @author Kai S. K. Engelbart
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public class ObjectWriteProxy {
|
|
|
|
private final WriteProxy writeProxy;
|
|
|
|
/**
|
|
* 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 IOException if the serialization of the object failed
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public void write(long recipientSocketId, Object obj) throws IOException {
|
|
// Create message targeted at the client
|
|
Message response = writeProxy.getMessage();
|
|
response.socketId = recipientSocketId;
|
|
|
|
// Serialize object to byte array
|
|
byte[] objBytes = SerializationUtils.writeToByteArray(obj);
|
|
|
|
// Acquire object length in bytes
|
|
byte[] objLen = SerializationUtils.intToBytes(objBytes.length);
|
|
|
|
response.writeToMessage(objLen);
|
|
response.writeToMessage(objBytes);
|
|
writeProxy.enqueue(response);
|
|
}
|
|
}
|