⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nioutils.java

📁 一套MMORPG手机网络游戏的服务端
💻 JAVA
字号:
/*
 * Created on 2005-4-20
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.swing.server.common;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.util.Iterator;

/**
 * @author vampire_a
 * 
 * NIO辅助操作包
 */
public class NIOUtils {

    /**
     * first, writes the header, then the event into the given ByteBuffer in
     * preparation for the channel write
     */
    public static void prepBuffer(GameEvent event, ByteBuffer writeBuffer) {
        try {
            /*
            writeBuffer.putInt(0); // todo: clientId
            if (event.getGameCode() != null)
                writeBuffer.putChar(event.getGameCode().charAt(0));
            else
                writeBuffer.putInt(0);
            int sizePos = writeBuffer.position();
            writeBuffer.putInt(0);// placeholder for payload size
            // write event
            int payloadSize = event.write(writeBuffer);

            // insert the payload size in the placeholder spot
            writeBuffer.putInt(sizePos, payloadSize);
            */
            byte [] mess = null;
            writeBuffer.clear();
            byte length = (byte) event.getResponse().size();
            writeBuffer.put(length);
            
            for (Iterator iter = event.getResponse().iterator(); iter.hasNext();) {
                Object data = iter.next();
                // 信息是String类型
                if (data.getClass().toString().equals("class java.lang.String")) {
                    mess = ((String) data ).getBytes("UTF-8");
                    writeBuffer.put((byte) 1);
                    writeBuffer.putShort((short) mess.length);
                    writeBuffer.put(mess);
                //    System.out.println ("NIOUtils --> prepBuffer --> output String = " + data);
                }
                // 信息是byte[]
                else if (data.getClass().toString().equals("class [B")) {
                    mess = (byte []) data;
                    writeBuffer.put((byte) 2);
                    writeBuffer.putShort((short) mess.length);
                    writeBuffer.put(mess);
                //    System.out.println ("NIOUtils --> prepBuffer --> output byte [] length = " + mess.length);
                }
            }
            writeBuffer.flip();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // prepare for a channel.write
        
    }

    /**
     * write the contents of a ByteBuffer to the given SocketChannel
     */
    public static void channelWrite(SocketChannel channel,
            ByteBuffer writeBuffer) {
        long nbytes = 0;
        long toWrite = writeBuffer.remaining();

        // loop on the channel.write() call since it will not necessarily
        // write all bytes in one shot
        try {
            while (nbytes != toWrite) {
                nbytes += channel.write(writeBuffer);

                try {
                    Thread.sleep(Globals.CHANNEL_WRITE_SLEEP);
                } catch (InterruptedException e) {
                }
            }
        } catch (ClosedChannelException cce) {
        } catch (Exception e) {
        }

        // get ready for another write if needed
        writeBuffer.rewind();
    }

    /**
     * write a String to a ByteBuffer, prepended with a short integer
     * representing the length of the String
     */
    public static void putStr(ByteBuffer buff, String str) {
        if (str == null) {
            buff.putShort((short) 0);
        } else {
            buff.putShort((short) str.length());
            buff.put(str.getBytes());
        }
    }

    /**
     * read a String from a ByteBuffer that was written w/the putStr method
     */
    public static String getStrByBlank(ByteBuffer buff) {
        /*
        short len = buff.getShort();
        if (len == 0) {
            return null;
        } else {
            byte[] b = new byte[len];
            buff.get(b);
            return new String(b);
        }
        */
        String s = null;
        try {
            s = HTTPUtils.decoder.decode(buff).toString();
        } catch (CharacterCodingException cce) {
            cce.printStackTrace();
        }
        return s.substring(0, s.indexOf(" "));
    }
    
    public static String getRemaining(ByteBuffer buff) {
        String s = null;
        try {
            s = HTTPUtils.decoder.decode(buff).toString();
        } catch (CharacterCodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return s;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -