本文整理汇总了Java中org.eclipse.jetty.websocket.api.WriteCallback类的典型用法代码示例。如果您正苦于以下问题:Java WriteCallback类的具体用法?Java WriteCallback怎么用?Java WriteCallback使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WriteCallback类属于org.eclipse.jetty.websocket.api包,在下文中一共展示了WriteCallback类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: outgoingFrame
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
@Override
public void outgoingFrame(Frame frame, WriteCallback callback, BatchMode batchMode)
{
// We use a queue and an IteratingCallback to handle concurrency.
// We must compress and write atomically, otherwise the compression
// context on the other end gets confused.
if (flusher.isFailed())
{
notifyCallbackFailure(callback,new ZipException());
return;
}
FrameEntry entry = new FrameEntry(frame,callback,batchMode);
if (LOG.isDebugEnabled())
LOG.debug("Queuing {}",entry);
offerEntry(entry);
flusher.iterate();
}
示例2: sendMessage
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
/**
* Send a message assynchronously.
*/
public void sendMessage(String message,WriteCallback callback) {
assertSessionOrFuture();
if (this.session!=null) {
this.session.getRemote().sendString(message,callback);
}
else if (this.futureSession!=null) {
// If connection has not completed yet, chain a new task that
// will wait for completion and then will try to send the message
// afterwards.
this.futureSession =
this.futureSession.thenApply((session)->{session.getRemote().sendString(message,callback);return session;});
}
else {
log.log(Level.SEVERE,"Could not send message to "+getHost()+" because there is no session neither a future session!");
}
}
示例3: offerMessage
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
/**
* @see ClientConnection#offerMessage(ServerToClient)
*/
public boolean offerMessage(ServerToClient message) {
Session session = getSession();
if (session == null || !session.isOpen()) return false;
if (inFlightMessages.incrementAndGet() > MAX_IN_FLIGHT_MESSAGES) {
inFlightMessages.decrementAndGet();
return false;
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(stream, null);
writeToClient.write(message, encoder);
encoder.flush();
} catch (Exception e) {
log.warn("Failed to encode message to client", e);
session.close(StatusCode.SERVER_ERROR, "Internal server error");
return true;
}
session.getRemote().sendBytes(ByteBuffer.wrap(stream.toByteArray()), new WriteCallback() {
@Override
public void writeSuccess() {
inFlightMessages.decrementAndGet();
}
@Override
public void writeFailed(Throwable error) {
inFlightMessages.decrementAndGet();
log.info("Sending message to WebSocket client failed: ", error);
}
});
return true;
}
示例4: send
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
@Override
public Promise<Void> send(final String message) {
_handler.handleMessageSending(message);
final Deferred<Void> deferred = new Deferred<>();
_session.getRemote().sendString(message, new WriteCallback() {
@Override
public void writeSuccess() {
deferred.setSuccess(null);
}
@Override
public void writeFailed(final Throwable cause) {
deferred.setFailure(cause);
}
});
return deferred;
}
示例5: notifyCallbackSuccess
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
protected void notifyCallbackSuccess(WriteCallback callback)
{
try
{
if (callback != null)
callback.writeSuccess();
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while notifying success of callback " + callback,x);
}
}
示例6: notifyCallbackFailure
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
protected void notifyCallbackFailure(WriteCallback callback, Throwable failure)
{
try
{
if (callback != null)
callback.writeFailed(failure);
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while notifying failure of callback " + callback,x);
}
}
示例7: sendMessage
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
public void sendMessage(String address, int port, String message, Runnable onSuccess, Consumer<Throwable> onFailure) throws Exception {
WebSocketHandlerImpl active_session = getConnection(address, port);
if (active_session==null)
return;
active_session.sendMessage(message,new WriteCallback() {
@Override
public void writeSuccess() {
onSuccess.run();
}
@Override
public void writeFailed(Throwable paramThrowable) {
onFailure.accept(paramThrowable);
}
});
}
示例8: ontext
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
@Test
public void ontext() {
performer.clientListener(new WebSocketAdapter() {
@Override
public void onWebSocketConnect(Session sess) {
sess.getRemote().sendString("A road of winds the water builds", new WriteCallback() {
@Override
public void writeSuccess() {
assertThat(true, is(true));
}
@Override
public void writeFailed(Throwable x) {
assertThat(true, is(false));
}
});
}
})
.onserver(new Action<ServerWebSocket>() {
@Override
public void on(ServerWebSocket ws) {
ws.ontext(new Action<String>() {
@Override
public void on(String data) {
assertThat(data, is("A road of winds the water builds"));
performer.start();
}
});
}
})
.connect();
}
示例9: onbinary
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
@Test
public void onbinary() {
performer.clientListener(new WebSocketAdapter() {
@Override
public void onWebSocketConnect(Session sess) {
sess.getRemote().sendBytes(ByteBuffer.wrap(new byte[] { 0x00, 0x01, 0x02 }), new WriteCallback() {
@Override
public void writeSuccess() {
assertThat(true, is(true));
}
@Override
public void writeFailed(Throwable x) {
assertThat(true, is(false));
}
});
}
})
.onserver(new Action<ServerWebSocket>() {
@Override
public void on(ServerWebSocket ws) {
ws.onbinary(new Action<ByteBuffer>() {
@Override
public void on(ByteBuffer data) {
assertThat(data, is(ByteBuffer.wrap(new byte[] { 0x00, 0x01, 0x02 })));
performer.start();
}
});
}
})
.connect();
}
示例10: sendMessage
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
@Override
public void sendMessage(WampMessage message, IWampConnectionPromise<Void> promise)
{
try {
String rawMessage = objectMapper.writeValueAsString(message.toObjectArray(objectMapper));
logger.debug("[CLIENT] Sending WAMP message {}", rawMessage);
session.getRemote().sendString(rawMessage,
new WriteCallback()
{
@Override
public void writeFailed(Throwable x)
{
promise.reject(x);
logger.error("[CLIENT] failed to send WAMP message", x);
}
@Override
public void writeSuccess()
{
promise.fulfill(null);
logger.debug("[CLIENT] WAMP message sent");
}
});
}catch (WampError | JsonProcessingException | RuntimeException e) {
logger.error("Failed to send message", e);
promise.reject(e);
}
}
示例11: FrameEntry
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
private FrameEntry(Frame frame, WriteCallback callback, BatchMode batchMode)
{
this.frame = frame;
this.callback = callback;
this.batchMode = batchMode;
}
示例12: receiveMessage
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
private void receiveMessage() {
if (log.isDebugEnabled()) {
log.debug("[{}:{}] [{}] [{}] Receive next message", request.getRemoteAddr(), request.getRemotePort(), topic, subscription);
}
reader.readNextAsync().thenAccept(msg -> {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] [{}] Got message {}", getSession().getRemoteAddress(), topic, subscription,
msg.getMessageId());
}
ConsumerMessage dm = new ConsumerMessage();
dm.messageId = Base64.getEncoder().encodeToString(msg.getMessageId().toByteArray());
dm.payload = Base64.getEncoder().encodeToString(msg.getData());
dm.properties = msg.getProperties();
dm.publishTime = DateFormatter.format(msg.getPublishTime());
if (msg.getEventTime() != 0) {
dm.eventTime = DateFormatter.format(msg.getEventTime());
}
if (msg.hasKey()) {
dm.key = msg.getKey();
}
final long msgSize = msg.getData().length;
try {
getSession().getRemote()
.sendString(ObjectMapperFactory.getThreadLocal().writeValueAsString(dm), new WriteCallback() {
@Override
public void writeFailed(Throwable th) {
log.warn("[{}/{}] Failed to deliver msg to {} {}", reader.getTopic(), subscription,
getRemote().getInetSocketAddress().toString(), th.getMessage());
pendingMessages.decrementAndGet();
// schedule receive as one of the delivery failed
service.getExecutor().execute(() -> receiveMessage());
}
@Override
public void writeSuccess() {
if (log.isDebugEnabled()) {
log.debug("[{}/{}] message is delivered successfully to {} ", reader.getTopic(),
subscription, getRemote().getInetSocketAddress().toString());
}
updateDeliverMsgStat(msgSize);
}
});
} catch (JsonProcessingException e) {
close(WebSocketError.FailedToSerializeToJSON);
}
int pending = pendingMessages.incrementAndGet();
if (pending < maxPendingMessages) {
// Start next read in a separate thread to avoid recursion
service.getExecutor().execute(() -> receiveMessage());
}
}).exceptionally(exception -> {
log.warn("[{}/{}] Failed to deliver msg to {} {}", reader.getTopic(),
subscription, getRemote().getInetSocketAddress().toString(), exception);
return null;
});
}
示例13: receiveMessage
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
private void receiveMessage() {
if (log.isDebugEnabled()) {
log.debug("[{}:{}] [{}] [{}] Receive next message", request.getRemoteAddr(), request.getRemotePort(), topic, subscription);
}
consumer.receiveAsync().thenAccept(msg -> {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] [{}] Got message {}", getSession().getRemoteAddress(), topic, subscription,
msg.getMessageId());
}
ConsumerMessage dm = new ConsumerMessage();
dm.messageId = Base64.getEncoder().encodeToString(msg.getMessageId().toByteArray());
dm.payload = Base64.getEncoder().encodeToString(msg.getData());
dm.properties = msg.getProperties();
dm.publishTime = DateFormatter.format(msg.getPublishTime());
if (msg.getEventTime() != 0) {
dm.eventTime = DateFormatter.format(msg.getEventTime());
}
if (msg.hasKey()) {
dm.key = msg.getKey();
}
final long msgSize = msg.getData().length;
try {
getSession().getRemote()
.sendString(ObjectMapperFactory.getThreadLocal().writeValueAsString(dm), new WriteCallback() {
@Override
public void writeFailed(Throwable th) {
log.warn("[{}/{}] Failed to deliver msg to {} {}", consumer.getTopic(), subscription,
getRemote().getInetSocketAddress().toString(), th.getMessage());
pendingMessages.decrementAndGet();
// schedule receive as one of the delivery failed
service.getExecutor().execute(() -> receiveMessage());
}
@Override
public void writeSuccess() {
if (log.isDebugEnabled()) {
log.debug("[{}/{}] message is delivered successfully to {} ", consumer.getTopic(),
subscription, getRemote().getInetSocketAddress().toString());
}
updateDeliverMsgStat(msgSize);
}
});
} catch (JsonProcessingException e) {
close(WebSocketError.FailedToSerializeToJSON);
}
int pending = pendingMessages.incrementAndGet();
if (pending < maxPendingMessages) {
// Start next read in a separate thread to avoid recursion
service.getExecutor().execute(() -> receiveMessage());
}
}).exceptionally(exception -> {
return null;
});
}
示例14: writeBytes
import org.eclipse.jetty.websocket.api.WriteCallback; //导入依赖的package包/类
@Override
public synchronized void writeBytes(Address toAddress,
byte[] message,
long timeout,
TimeUnit unit,
final SuccessAction successAction,
final FailureAction failureAction) {
if (!(toAddress instanceof WebSocketClientAddress)) {
throw new JoynrIllegalStateException("Web Socket Server can only send to WebSocketClientAddresses");
}
WebSocketClientAddress toClientAddress = (WebSocketClientAddress) toAddress;
Session session = sessionMap.get(toClientAddress.getId());
if (session == null) {
//TODO We need a delay with invalidation of the stub
throw new JoynrDelayMessageException("no active session for WebSocketClientAddress: "
+ toClientAddress.getId());
}
try {
session.getRemote().sendBytes(ByteBuffer.wrap(message), new WriteCallback() {
@Override
public void writeSuccess() {
successAction.execute();
}
@Override
public void writeFailed(Throwable error) {
if (shutdown) {
return;
}
failureAction.execute(error);
}
});
} catch (WebSocketException e) {
// Jetty throws WebSocketException when expecting [OPEN or CONNECTED] but found a different state
// The client must reconnect, but the message can be queued in the mean time.
sessionMap.remove(toClientAddress.getId());
//TODO We need a delay with invalidation of the stub
throw new JoynrDelayMessageException(e.getMessage(), e);
}
}