本文整理汇总了Java中org.apache.mina.core.future.IoFuture类的典型用法代码示例。如果您正苦于以下问题:Java IoFuture类的具体用法?Java IoFuture怎么用?Java IoFuture使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
IoFuture类属于org.apache.mina.core.future包,在下文中一共展示了IoFuture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: encode
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
@Override
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
try {
byte compressedBytes[] = (byte[]) message;
final IoBuffer buffer = IoBuffer.allocate(compressedBytes.length).setAutoExpand(true);
buffer.put(compressedBytes);
buffer.flip();
out.write(buffer);
WriteFuture wf = out.flush();
wf.addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
buffer.free();
}
});
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
示例2: load
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
/**
* Loads a player's game in the work service.
* @param pd The player's details.
*/
public void load(final PlayerDetails pd) {
engine.submitWork(new Runnable() {
public void run() {
LoginResult lr = loader.checkLogin(pd);
int code = lr.getReturnCode();
if(!NameUtils.isValidName(pd.getName())) {
code = 11;
}
if(code != 2) {
PacketBuilder bldr = new PacketBuilder();
bldr.put((byte) code);
pd.getSession().write(bldr.toPacket()).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
future.getSession().close(false);
}
});
} else {
lr.getPlayer().getSession().setAttribute("player", lr.getPlayer());
loader.loadPlayer(lr.getPlayer());
engine.pushTask(new SessionLoginTask(lr.getPlayer()));
}
}
});
}
示例3: awaitUninterruptibly
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
public static boolean awaitUninterruptibly(Iterable<? extends IoFuture> futures, long timeoutMillis) {
try {
return await0(futures, timeoutMillis, false);
} catch (InterruptedException e) {
throw new InternalError();
}
}
示例4: await0
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
private static boolean await0(Iterable<? extends IoFuture> futures, long timeoutMillis, boolean interruptable)
throws InterruptedException {
long startTime = timeoutMillis <= 0 ? 0 : System.currentTimeMillis();
long waitTime = timeoutMillis;
boolean lastComplete = true;
Iterator<? extends IoFuture> i = futures.iterator();
while (i.hasNext()) {
IoFuture f = i.next();
do {
if (interruptable) {
lastComplete = f.await(waitTime);
} else {
lastComplete = f.awaitUninterruptibly(waitTime);
}
waitTime = timeoutMillis - (System.currentTimeMillis() - startTime);
if (lastComplete || waitTime <= 0) {
break;
}
} while (!lastComplete);
if (waitTime <= 0) {
break;
}
}
return lastComplete && !i.hasNext();
}
示例5: disconnectSessions
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
/**
* Close all the sessions
* TODO disconnectSessions.
*
*/
private void disconnectSessions() {
if (!(service instanceof IoAcceptor)) {
// We don't disconnect sessions for anything but an Acceptor
return;
}
if (!((IoAcceptor) service).isCloseOnDeactivation()) {
return;
}
Object lock = new Object();
IoFutureListener<IoFuture> listener = new LockNotifyingListener(lock);
for (IoSession s : managedSessions.values()) {
s.close(true).addListener(listener);
}
try {
synchronized (lock) {
while (!managedSessions.isEmpty()) {
lock.wait(500);
}
}
} catch (InterruptedException ie) {
// Ignored
}
}
示例6: sendRequest
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception {
final long beginTime = System.currentTimeMillis();
WriteFuture writeFuture = session.write(wrapper);
final Client self = this;
writeFuture.addListener(new IoFutureListener() {
public void operationComplete(IoFuture future) {
WriteFuture wfuture = (WriteFuture) future;
if (wfuture.isWritten()) {
return;
}
String error = "send message to server: " + session.getRemoteAddress()
+ " error,maybe because sendbuffer is full or connection closed: " + !session.isConnected();
if (System.currentTimeMillis() - beginTime >= timeout) {
error = "write message to os send buffer timeout,consumetime is: " + (System.currentTimeMillis() - beginTime) + "ms,timeout is:"
+ timeout;
}
LOGGER.error(error);
ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(), wrapper.getProtocolType());
response.setException(new Exception(error));
try {
putResponse(response);
} catch (Exception e) {
// IGNORE, should not happen
}
if (session.isConnected()) {
if (isWarnEnabled) {
LOGGER.warn("close the session because send request error,server:" + session.getRemoteAddress());
}
session.closeNow();
} else {
// TODO: exception handle
MinaClientFactory.getInstance().removeClient(key, self);
}
}
});
}
示例7: sendErrorResponse
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
private void sendErrorResponse(final IoSession session, final RequestWrapper request) {
ResponseWrapper responseWrapper = new ResponseWrapper(request.getId(), request.getCodecType(), request.getProtocolType());
responseWrapper.setException(new Exception("server threadpool full,maybe because server is slow or too many requests"));
WriteFuture wf = session.write(responseWrapper);
wf.addListener(new IoFutureListener() {
public void operationComplete(IoFuture future) {
if (!((WriteFuture) future).isWritten()) {
LOGGER.error("server write response error,request id is: " + request.getId());
}
}
});
}
示例8: run
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
public void run() {
// pipeline
if (message instanceof List) {
List messages = (List) message;
for (Object messageObject : messages) {
threadPool.execute(new HandlerRunnable(session, messageObject, threadPool));
}
} else {
RequestWrapper request = (RequestWrapper) message;
long beginTime = System.currentTimeMillis();
ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType()).handleRequest(request);
final int id = request.getId();
// already timeout,so not return
if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
LOGGER.warn("timeout,so give up send response to client,requestId is:" + id + ",client is:" + session.getRemoteAddress()
+ ",consumetime is:" + (System.currentTimeMillis() - beginTime) + ",timeout is:" + request.getTimeout());
return;
}
WriteFuture wf = session.write(responseWrapper);
wf.addListener(new IoFutureListener() {
public void operationComplete(IoFuture future) {
if (!((WriteFuture) future).isWritten()) {
LOGGER.error("server write response error,request id is: " + id);
}
}
});
}
}
示例9: register
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
/**
* Registers a new player.
* @param player The player to register.
*/
public void register(final Player player) {
// do final checks e.g. is player online? is world full?
int returnCode = 2;
if(isPlayerOnline(player.getName())) {
returnCode = 5;
} else {
if(!players.add(player)) {
returnCode = 7;
logger.info("Could not register player : " + player + " [world full]");
}
}
final int fReturnCode = returnCode;
PacketBuilder bldr = new PacketBuilder();
bldr.put((byte) returnCode);
bldr.put((byte) player.getRights().toInteger());
bldr.put((byte) 0);
player.getSession().write(bldr.toPacket()).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
if(fReturnCode != 2) {
player.getSession().close(false);
} else {
player.getActionSender().sendLogin();
}
}
});
if(returnCode == 2) {
logger.info("Registered player : " + player + " [online=" + players.size() + "]");
}
}
示例10: serve
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
/**
* Servers the requested file.
*/
private void serve() {
if(request == null) {
session.close(false);
return;
}
logger.fine("Serving " + type + " request : " + request.getPath());
Response resp = RequestHandler.handle(request);
if(resp == null) {
session.close(false);
return;
}
StringBuilder header = new StringBuilder();
if(type == Type.HTTP) {
header.append("HTTP/1.0 200 OK\r\n");
header.append("Content-Length: ").append(resp.getFileData().remaining()).append("\r\n");
header.append("Connection: close\r\n");
header.append("Server: JaGeX/3.1\r\n");
header.append("Content-Type: " + resp.getMimeType() + "\r\n");
header.append("\r\n");
}
byte[] headerBytes = header.toString().getBytes();
ByteBuffer bb = resp.getFileData();
IoBuffer ib = IoBuffer.allocate(bb.remaining() + headerBytes.length);
ib.put(headerBytes).put(bb);
ib.flip();
session.write(ib).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture arg0) {
session.close(false);
}
});
}
示例11: initSession
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
protected final void initSession(NioSession session, IoFuture future) {
// Every property but attributeMap should be set now. Now initialize the attributeMap.
// The reason why we initialize the attributeMap at last is to make sure all session properties
// such as remoteAddress are provided to IoSessionDataStructureFactory.
session.setAttributeMap(session.getService().getSessionDataStructureFactory().getAttributeMap(session));
session.setWriteRequestQueue(session.getService().getSessionDataStructureFactory().getWriteRequestQueue(session));
if (future instanceof ConnectFuture) {
// DefaultIoFilterChain will notify the future. (We support ConnectFuture only for now).
session.setAttribute(DefaultIoFilterChain.SESSION_CREATED_FUTURE, future);
}
finishSessionInitialization0(session, future);
}
示例12: finishSessionInitialization0
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
/**
* Adds required internal attributes and {@link IoFutureListener}s related with event notifications
* to the specified {@code session} and {@code future}. Do not call this method directly;
*/
@Override
protected final void finishSessionInitialization0(IoSession session, IoFuture future) {
// In case that ConnectFuture.cancel() is invoked before setSession() is invoked,
// add a listener that closes the connection immediately on cancellation.
future.addListener((ConnectFuture future1) -> {
if (future1.isCanceled()) {
session.closeNow();
}
});
}
示例13: operationComplete
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
public void operationComplete(IoFuture future) {
synchronized (TAKEN_LOCAL_ADDRESSES) {
TAKEN_LOCAL_ADDRESSES.remove(future.getSession().getLocalAddress());
}
}
示例14: doFinishSessionInitialization
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
void doFinishSessionInitialization(IoSession session, IoFuture future) {
initSession(session, future, null);
}
示例15: await
import org.apache.mina.core.future.IoFuture; //导入依赖的package包/类
public static void await(Iterable<? extends IoFuture> futures) throws InterruptedException {
for (IoFuture f : futures) {
f.await();
}
}