本文整理汇总了Java中org.apache.mina.common.ByteBuffer类的典型用法代码示例。如果您正苦于以下问题:Java ByteBuffer类的具体用法?Java ByteBuffer怎么用?Java ByteBuffer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ByteBuffer类属于org.apache.mina.common包,在下文中一共展示了ByteBuffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: decode
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
throws ProtocolCodecException {
int messageCount = 0;
while (parseMessage(in, out)) {
messageCount++;
}
if (messageCount > 0) {
// Mina will compact the buffer because we can't detect a header
if (in.remaining() < HEADER_PATTERN.length) {
position = 0;
}
return MessageDecoderResult.OK;
} else {
// Mina will compact the buffer
position -= in.position();
return MessageDecoderResult.NEED_DATA;
}
}
示例2: run_startup_configurations
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static void run_startup_configurations() {
ip = ServerConfig.IP_ADDRESS + ":" + PORT;
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
acceptor = new SocketAcceptor();
final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.getSessionConfig().setTcpNoDelay(true);
cfg.setDisconnectOnUnbind(true);
cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
players = new PlayerStorage(-10);
try {
InetSocketadd = new InetSocketAddress(PORT);
acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
System.out.println("Cash Shop Server is listening on port " + PORT + ".");
} catch (final IOException e) {
System.out.println(" Failed!");
System.err.println("Could not bind to port " + PORT + ".");
throw new RuntimeException("Binding failed.", e);
}
}
示例3: run_startup_configurations
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static final void run_startup_configurations() {
userLimit = ServerConfig.USER_LIMIT;
serverName = ServerConfig.SERVER_NAME;
eventMessage = ServerConfig.EVENT_MSG;
maxCharacters = ServerConfig.MAX_CHARACTERS;
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
acceptor = new SocketAcceptor();
final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.getSessionConfig().setTcpNoDelay(true);
cfg.setDisconnectOnUnbind(true);
cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
try {
InetSocketadd = new InetSocketAddress(8484);
acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
System.out.println("Login Server is listening on port 8484.");
} catch (IOException e) {
System.out.println(" Failed!");
System.err.println("Could not bind to port 8484: " + e);
}
}
示例4: encode
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
@Override
public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception {
final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);
if (client != null) {
final byte[] input = ((MaplePacket) message).getBytes();
final byte[] unencrypted = new byte[input.length];
System.arraycopy(input, 0, unencrypted, 0, input.length);
final byte[] ret = new byte[unencrypted.length + 4];
final byte[] header = client.getSendCrypto().getPacketHeader(unencrypted.length);
synchronized(client.getSendCrypto()){
MapleCustomEncryption.encryptData(unencrypted);
client.getSendCrypto().crypt(unencrypted);
System.arraycopy(header, 0, ret, 0, 4);
System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length);
final ByteBuffer out_buffer = ByteBuffer.wrap(ret);
out.write(out_buffer);
}
} else { // no client object created yet, send unencrypted (hello)
out.write(ByteBuffer.wrap(((MaplePacket) message).getBytes()));
}
}
示例5: encode
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
if(!(message instanceof byte[])){
throw new Exception("must send byte[]");
}
byte[] payload=(byte[]) message;
ByteBuffer buf = ByteBuffer.allocate(payload.length, false);
buf.put(payload);
buf.flip();
out.write(buf);
if (isDebugEnabled)
LOGGER.debug(TairUtil.toHex(payload));
}
示例6: appendDebugInformation
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
private String appendDebugInformation(ByteBuffer buffer, String text) {
int mark = buffer.position();
try {
StringBuilder sb = new StringBuilder(text);
sb.append("\nBuffer debug info: ").append(getBufferDebugInfo(buffer));
buffer.position(0);
sb.append("\nBuffer contents: ");
try {
final byte[] array = new byte[buffer.limit()];
for(int i = 0; i < array.length; ++i)
array[i] = buffer.get();
sb.append(new String(array, "ISO-8859-1"));
} catch (Exception e) {
sb.append(buffer.getHexDump());
}
text = sb.toString();
} finally {
buffer.position(mark);
}
return text;
}
示例7: startsWith
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
private static boolean startsWith(ByteBuffer buffer, int bufferOffset, byte[] data) {
try {
if (bufferOffset + data.length > buffer.limit()) {
return false;
}
//StringBuffer sb = new StringBuffer();
for (int dataOffset = 0; dataOffset < data.length && bufferOffset < buffer.limit(); dataOffset++, bufferOffset++) {
byte b = buffer.get(bufferOffset);
if(b == '\r' && dataOffset > 0 && buffer.get(bufferOffset - 1) == '\u0001') {
return true; // EOF io
}
byte bPatern = data[dataOffset];
if (b != bPatern && bPatern != '?') {
return false;
}
}
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
示例8: extractMessages
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
/**
* Utility to extract messages from a file. This method will return each
* message found to a provided listener. The message file will also be
* memory mapped rather than fully loaded into physical memory. Therefore,
* a large message file can be processed without using excessive memory.
*
* @param file
* @param listener
* @throws IOException
* @throws ProtocolCodecException
*/
public void extractMessages(File file, final MessageListener listener) throws IOException,
ProtocolCodecException {
// Set up a read-only memory-mapped file
FileChannel readOnlyChannel = new RandomAccessFile(file, "r").getChannel();
MappedByteBuffer memoryMappedBuffer = readOnlyChannel.map(FileChannel.MapMode.READ_ONLY, 0,
(int) readOnlyChannel.size());
decode(null, ByteBuffer.wrap(memoryMappedBuffer), new ProtocolDecoderOutput() {
public void write(Object message) {
listener.onMessage((String) message);
}
public void flush() {
// ignored
}
});
}
示例9: readShortString
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static String readShortString(ByteBuffer buffer)
{
short length = buffer.getUnsigned();
if (length == 0)
{
return null;
}
else
{
// this may seem rather odd to declare two array but testing has shown
// that constructing a string from a byte array is 5 (five) times slower
// than constructing one from a char array.
// this approach here is valid since we know that all the chars are
// ASCII (0-127)
byte[] stringBytes = new byte[length];
buffer.get(stringBytes, 0, length);
char[] stringChars = new char[length];
for (int i = 0; i < stringChars.length; i++)
{
stringChars[i] = (char) stringBytes[i];
}
return new String(stringChars);
}
}
示例10: messageReceived
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
// Decode the bytebuffer and print it to the stdout
if (enabled && message instanceof ByteBuffer) {
ByteBuffer byteBuffer = (ByteBuffer) message;
// Keep current position in the buffer
int currentPos = byteBuffer.position();
// Decode buffer
Charset encoder = Charset.forName("UTF-8");
CharBuffer charBuffer = encoder.decode(byteBuffer.buf());
// Print buffer content
System.out.println(prefix + " - RECV (" + session.hashCode() + "): " + charBuffer);
// Reset to old position in the buffer
byteBuffer.position(currentPos);
}
// Pass the message to the next filter
super.messageReceived(nextFilter, session, message);
}
示例11: writeToBuffer
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public void writeToBuffer(ByteBuffer buffer)
{
final boolean trace = _logger.isDebugEnabled();
if (trace)
{
_logger.debug("FieldTable::writeToBuffer: Writing encoded length of " + getEncodedSize() + "...");
if (_properties != null)
{
_logger.debug(_properties.toString());
}
}
EncodingUtils.writeUnsignedInteger(buffer, getEncodedSize());
putDataInBuffer(buffer);
}
示例12: doDecodePI
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
/**
* Decodes an AMQP initiation, delegating the decoding to a {@link ProtocolInitiation.Decoder}.
*
* @param session The Mina session.
* @param in The raw byte buffer.
* @param out The Mina object output gatherer to write decoded objects to.
*
* @return <tt>true</tt> if the data was decoded, <tt>false<tt> if more is needed and the data should accumulate.
*
* @throws Exception If the data cannot be decoded for any reason.
*/
private boolean doDecodePI(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
{
boolean enoughData = _piDecoder.decodable(in.buf());
if (!enoughData)
{
// returning false means it will leave the contents in the buffer and
// call us again when more data has been read
return false;
}
else
{
ProtocolInitiation pi = new ProtocolInitiation(in.buf());
out.write(pi);
return true;
}
}
示例13: writeUTF
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public void writeUTF(String string) throws JMSException
{
checkWritable();
try
{
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
java.nio.ByteBuffer encodedString = encoder.encode(CharBuffer.wrap(string));
_data.putShort((short)encodedString.limit());
_data.put(encodedString);
_changedData = true;
//_data.putString(string, Charset.forName("UTF-8").newEncoder());
// we must add the null terminator manually
//_data.put((byte)0);
}
catch (CharacterCodingException e)
{
JMSException jmse = new JMSException("Unable to encode string: " + e);
jmse.setLinkedException(e);
jmse.initCause(e);
throw jmse;
}
}
示例14: run_startup_configurations
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static void run_startup_configurations() {
System.out.print("Loading Cash Shop...");
ip = ServerConfig.interface_ + ":" + PORT;
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
acceptor = new SocketAcceptor();
final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.getSessionConfig().setTcpNoDelay(true);
cfg.setDisconnectOnUnbind(true);
cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
players = new PlayerStorage(-10);
try {
InetSocketadd = new InetSocketAddress(PORT);
acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
System.out.println(" Complete!");
System.out.println("Cash Shop Server is listening on port " + PORT + ".");
} catch (final IOException e) {
System.out.println(" Failed!");
System.err.println("Could not bind to port " + PORT + ".");
throw new RuntimeException("Binding failed.", e);
}
}
示例15: extractByteMessageContent
import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
/**
* Extract ByteMessage from ByteBuffer
*
* @param wrapMsgContent ByteBuffer which contains data
* @param byteMsgContent byte[] of message content
* @return extracted content as text
*/
private String extractByteMessageContent(ByteBuffer wrapMsgContent, byte[] byteMsgContent) {
String wholeMsg;
if (byteMsgContent == null) {
throw new IllegalArgumentException("byte array must not be null");
}
int count = (wrapMsgContent.remaining() >= byteMsgContent.length ?
byteMsgContent.length :
wrapMsgContent.remaining());
if (count == 0) {
wholeMsg = String.valueOf(-1);
} else {
wrapMsgContent.get(byteMsgContent, 0, count);
wholeMsg = String.valueOf(count);
}
return wholeMsg;
}