Java Code Examples for org.apache.mina.core.session.IoSession#write()

The following examples show how to use org.apache.mina.core.session.IoSession#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BceFindRoomHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceFindRoom");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseFindRoom.BseFindRoom.Builder builder = XinqiBseFindRoom.BseFindRoom.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceFindRoom.BceFindRoom)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceFindRoom: " + response);
}
 
Example 2
Source File: BceAcceptDailyAwardHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceAcceptDailyAward");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
   //TODO BseAcceptDailyAward not exists
	//XinqiBseAcceptDailyAward.BseAcceptDailyAward.Builder builder = XinqiBseAcceptDailyAward.BseAcceptDailyAward.newBuilder();
	//response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceAcceptDailyAward.BceAcceptDailyAward)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceAcceptDailyAward: " + response);
}
 
Example 3
Source File: SysMessageManager.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Send the raw message to client
 * @param messageKey
 */
public void sendClientInfoRawMessage(IoSession session, String message, Action action, Type type) {
	BseSysMessage.Builder builder = BseSysMessage.newBuilder();
	builder.setMessage(message);
	builder.setSeconds(SECONDS_INFO);
	switch ( action ) {
		case NOOP:
			builder.setAction(XinqiSysMessage.Action.NOOP);
			break;
		case EXIT_GAME:
			builder.setAction(XinqiSysMessage.Action.EXIT_GAME);
			break;
		case RECONNECT:
			builder.setAction(XinqiSysMessage.Action.RECONNECT);
			break;
	}
	builder.setType(type);
	BseSysMessage sysMessage = builder.build();
	
	if ( session != null ) {
		XinqiMessage xinqi = new XinqiMessage();
		xinqi.payload = sysMessage;
		session.write(xinqi);
	}
}
 
Example 4
Source File: BceUserGuidAtkHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceUserGuidAtk");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
   //TODO BseUserGuidAtk not exists
	//XinqiBseUserGuidAtk.BseUserGuidAtk.Builder builder = XinqiBseUserGuidAtk.BseUserGuidAtk.newBuilder();
	//response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceUserGuidAtk.BceUserGuidAtk)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceUserGuidAtk: " + response);
}
 
Example 5
Source File: BceBulletHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceBullet");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
   //TODO BseBullet not exists
	//XinqiBseBullet.BseBullet.Builder builder = XinqiBseBullet.BseBullet.newBuilder();
	//response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceBullet.BceBullet)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceBullet: " + response);
}
 
Example 6
Source File: BceGuildIronLevelupHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceGuildIronLevelup");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseGuildIronLevelup.BseGuildIronLevelup.Builder builder = XinqiBseGuildIronLevelup.BseGuildIronLevelup.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceGuildIronLevelup.BceGuildIronLevelup)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceGuildIronLevelup: " + response);
}
 
Example 7
Source File: BceGuildRequestHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceGuildRequest");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseGuildRequest.BseGuildRequest.Builder builder = XinqiBseGuildRequest.BseGuildRequest.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceGuildRequest.BceGuildRequest)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceGuildRequest: " + response);
}
 
Example 8
Source File: BceLeaveMessageHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceLeaveMessage");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseLeaveMessage.BseLeaveMessage.Builder builder = XinqiBseLeaveMessage.BseLeaveMessage.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceLeaveMessage.BceLeaveMessage)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceLeaveMessage: " + response);
}
 
Example 9
Source File: BceGuildPosChangeHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceGuildPosChange");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseGuildPosChange.BseGuildPosChange.Builder builder = XinqiBseGuildPosChange.BseGuildPosChange.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceGuildPosChange.BceGuildPosChange)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceGuildPosChange: " + response);
}
 
Example 10
Source File: BceGuildBuyHandler.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
public void messageProcess(IoSession session, Object message, SessionKey sessionKey)
		throws Exception {
	if ( log.isDebugEnabled() ) {
		log.debug("->BceGuildBuy");
	}
	
	XinqiMessage request = (XinqiMessage)message;
	XinqiMessage response = new XinqiMessage();
	XinqiBseGuildBuy.BseGuildBuy.Builder builder = XinqiBseGuildBuy.BseGuildBuy.newBuilder();
	response.payload = builder.build();
	//TODO BEGIN add logic here.
	//builder.setUid(((XinqiBceGuildBuy.BceGuildBuy)request.payload).getUid());
	//END
	session.write(response);
	System.out.println("BceGuildBuy: " + response);
}
 
Example 11
Source File: SessionMap.java    From mina with Apache License 2.0 5 votes vote down vote up
/**
 * 发送消息到客户端
 *
 * @param key
 * @param message
 */
public void sendMessage(String key, Object message) {
    IoSession session = getSession(key);

    log.debug("反向发送消息到客户端Session---key=" + key + "----------消息=" + message);
    if (session == null) {
        return ;
    }
    session.write(message);
}
 
Example 12
Source File: AccountManager.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * @param session
 */
private void sendLoginResponse(IoSession session, ErrorCode errorCode) {
	BseLogin.Builder loginRep = BseLogin.newBuilder();
	loginRep.setCode(errorCode.ordinal());
	loginRep.setDesc(Text.text(errorCode.desc()));
	XinqiMessage response = new XinqiMessage();
	response.payload = loginRep.build();
	session.write(response);
}
 
Example 13
Source File: MinaClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public Response sentSync(final Request request) throws Exception {
    final ConnectFuture connect = super.getConnect(request);
    if (connect != null && connect.isConnected()) {
        RpcFuture rpcFuture = new RpcFuture(request);
        //写数据
        connect.addListener(new AbstractClient.FutureListener(rpcFuture));
        IoSession session = connect.getSession();
        session.write(request);
        return rpcFuture.get();
    } else {
        throw new IllegalArgumentException("[JobX] MinaRPC channel not active. request id:" + request.getId());
    }
}
 
Example 14
Source File: ClientTestServer.java    From java-study with Apache License 2.0 5 votes vote down vote up
public void sendMsg(IoSession session,String msg){  
	
        HashMap<String,String> sy=new HashMap<String, String>();           
          sy.put("channel", "android");
          sy.put("deviceId", "12-ab");
          sy.put("device", "1456");
          sy.put("appVersion", "Version 1.5.1");
          sy.put("account", "This is test message");
        
          sy.put("ss","client_bind");
     //     logger.info("SentBody:"+sy);
       //   session.setAttribute("account","hello world");
          session.write(sy);// 发送消息 
}
 
Example 15
Source File: MinaClientService.java    From game-server with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * 发送消息
 */
public boolean sendMsg(Object obj) {
	IoSession session = getMostIdleIoSession();
	if (session != null) {
		session.write(obj);
		return true;
	}
	return false;
}
 
Example 16
Source File: ServerInfo.java    From game-server with MIT License 5 votes vote down vote up
public void sendMsg(Object message) {
	IoSession se = getSession();
	if (se != null) {
		se.write(message);
	} else if (getChannel() != null) {
		getChannel().writeAndFlush(message);
	} else {
		log.warn("服务器:" + name + "连接会话为空");
	}
}
 
Example 17
Source File: HttpServer.java    From jforgame with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionOpened(IoSession session) throws Exception {
	String ipAddr = SessionManager.INSTANCE.getRemoteIp(session);
	if (!isInWhiteIps(ipAddr)) {
		logger.error("非法后台登录,remoteIp=[{}]", ipAddr);
		byte[] body = "too young too simple".getBytes("UTF-8");
		IoBuffer out = IoBuffer.allocate(body.length);
		out.put(body);
		out.flip();
		session.write(out);
		session.close(false);
	}
}
 
Example 18
Source File: ITCHMulticastTCPHandlerAdapter.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private IMessage onReplay(IMessage iMessage, IoSession session) {
    Object firstMessage = iMessage.getField(FIRST_MESSAGE);
    Object count = iMessage.getField(COUNT);
    Object marketDataGroup = iMessage.getField(MARKET_DATA_GROUP);
    List<IMessage> messageList = new ArrayList<>();
    IMessage result = msgFactory.createMessage(REPLAY_RESPONSE, iMessage.getNamespace());
    result.addField(MARKET_DATA_GROUP, marketDataGroup);
    Status status = Status.REQUEST_ACCEPTED;
    if (firstMessage != null && count != null) {
        logger.debug("ReplayRequest works");
         status = cache.getMessages(Integer.valueOf(firstMessage.toString()), (Integer) count, new Byte(marketDataGroup.toString()), messageList);
        switch (status) {
            case REQUEST_ACCEPTED:
                result.addField(FIRST_MESSAGE, firstMessage);
                result.addField(COUNT, count);
                result.addField(STATUS, toShort('A'));
                break;
            case OUT_OF_RANGE:
                result.addField(FIRST_MESSAGE, (long)0);
                result.addField(COUNT, 0);
                result.addField(STATUS, toShort('O'));
                break;
            case INVALID_MARKET_DATA_GROUP:
                result.addField(FIRST_MESSAGE, firstMessage);
                result.addField(COUNT, count);
                result.addField(STATUS, toShort('I'));
                break;
            case REPLAY_UNAVAILABLE:
                result.addField(FIRST_MESSAGE, (long)0);
                result.addField(COUNT, 0);
                result.addField(STATUS, toShort('U'));
        }
    }
    @SuppressWarnings("serial")
    Map<String, String> params = new HashMap<String, String>(){{
        put(ITCHMessageHelper.FIELD_MARKET_DATA_GROUP_NAME, String.valueOf(marketDataGroup));
        put(ITCHMessageHelper.FIELD_SEQUENCE_NUMBER_NAME, String.valueOf(0));
    }};
    result = itchHandler.prepareMessageToEncode(result, params);
    session.write(result);
    handleMessage(result, false, false, session.getRemoteAddress().toString());
    if(status == Status.REQUEST_ACCEPTED) {
        for(IMessage msg:messageList){
            session.write(msg);
            handleMessage(msg, false, false, session.getRemoteAddress().toString());
        }
    }
    return result;
}
 
Example 19
Source File: HttpConfigHandler.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
	 * Receive the http request. Check its request uri.
	 */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		HttpMessage httpMessage = (HttpMessage)message;
		try {
			if ( httpMessage.getRequestUri() != null ) {
				String variable = null;
				if ( httpMessage.getRequestUri().indexOf('?') >= 0 ) {
					variable = substring(httpMessage.getRequestUri(), "?", null);
				}
				String url = substring(httpMessage.getRequestUri(), null, HTTP);
				String uri = substringR(url, PATH_SEP, QUESTION).trim();
				if ( log.isDebugEnabled() ) {
					log.debug("Request url: " + url + ".  uri: " + uri + ", variable: " + variable);
				}
				byte[] configData = null;
//				GameConfig gameConfig = gameContext.getGameConfig(uri);
//				if ( gameConfig != null ) {
//					BaseManager manager = gameConfig.getBaseManager(variable);
//					if ( manager != null ) {
//						httpMessage.setResponseLastModified(manager.getConfigLastModified());
//						configData = manager.getConfigCachedData();
//					} else {
//						configData = NOT_FOUND_VAR;
//					}
//					if ( log.isDebugEnabled() ) {
//						log.debug("Sent uri data to client");
//					}
//				} else {
//					log.warn("Failed to find the uri game config object: " + uri);
//				}
				httpMessage.setResponseContent(configData);
			} else {
				httpMessage.setResponseContent(NOT_FOUND_MSG);
			}
		} catch (Throwable e1) {
			e1.printStackTrace();
		}
		WriteFuture future = session.write(httpMessage);
		// We can wait for the client to close the socket.
//		future.addListener(IoFutureListener.CLOSE);
//		GameContext.getInstance().writeResponse(session, httpMessage);
	}
 
Example 20
Source File: ConnectorTest.java    From game-server with MIT License 4 votes vote down vote up
private void testConnector0(IoSession session) throws InterruptedException {
    EchoConnectorHandler handler = (EchoConnectorHandler) session
            .getHandler();
    IoBuffer readBuf = handler.readBuf;
    readBuf.clear();
    WriteFuture writeFuture = null;
    
    for (int i = 0; i < COUNT; i++) {
        IoBuffer buf = IoBuffer.allocate(DATA_SIZE);
        buf.limit(DATA_SIZE);
        fillWriteBuffer(buf, i);
        buf.flip();

        writeFuture = session.write(buf);

        if (session.getService().getTransportMetadata().isConnectionless()) {
            // This will align message arrival order in connectionless transport types
            waitForResponse(handler, (i + 1) * DATA_SIZE);
        }
    }

    writeFuture.awaitUninterruptibly();

    waitForResponse(handler, DATA_SIZE * COUNT);

    // Assert data
    //// Please note that BufferOverflowException can be thrown
    //// in SocketIoProcessor if there was a read timeout because
    //// we share readBuf.
    readBuf.flip();
    LOGGER.info("readBuf: " + readBuf);
    assertEquals(DATA_SIZE * COUNT, readBuf.remaining());
    IoBuffer expectedBuf = IoBuffer.allocate(DATA_SIZE * COUNT);
    
    for (int i = 0; i < COUNT; i++) {
        expectedBuf.limit((i + 1) * DATA_SIZE);
        fillWriteBuffer(expectedBuf, i);
    }
    
    expectedBuf.position(0);

    isEquals(expectedBuf, readBuf);
}