NIOではByteBufferについて簡単に使います。


1.NIOnew Socket(ip,port)との接続を確立する。
*2.Scanner.nextを取得する(System.in):入力内容
*3.送信する文字列の内容を処理する
*    a.int len=str.getByte().lengthを取得する
*    b.lenをbyte処理し、順次serverに送る
*    dos.write((byte)temps.length&0 xff);
dos.write((byte)temps.length>>8&0 xff)
*    c.データ自体をNioServerに送信する
*    NIOserverはByteBufferを使ってデータを受信するため、クライアントではバイトフロー方式を採用し、Bytte演算を行ってから、ネットワークフローに送信することができます。
2.サーバー類が多いので、ここから関連するbyteBufferの処理コードを貼り付けます。
クライアントコード

/**
 * 
 */
package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


/**
 * @author sean
 * 
 *   NIOServer     
 * 1. NIOServer    new Socket(ip, port) 
 * 2.  Scanner.next(System.in):    
 * 3.               
 *    a.   int len = str.getByte().length
 *    b.  len   byte   ,    server
 *    	dos.write((byte)temps.length&0xff);
		dos.write((byte)temps.length>>8&0xff);
 *    c.         NioServer
 *      :  NIOserver  ByteBuffer     ,  ,             ,    Byte   ,         
 *    
 * *
 */
public class ClientDemo {

	static Socket socket;	
	static DataOutputStream dos;
	
	static DataInputStream dis;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			socket = new Socket("127.0.0.1", 9999);		
			if(socket == null){
				System.exit(0);
			}
			dos = new DataOutputStream(socket.getOutputStream());
			dis = new DataInputStream(socket.getInputStream());	

			//         
			Scanner sc = new Scanner(System.in);			
			
			do{
				System.out.println("please enter content:");
				String msg = sc.next();
				System.out.println("length:" + msg.getBytes().length);
				
				//       utf-8        
				byte temps[]=msg.getBytes("UTF-8");
				
				// length     ,   short ,              ,  
				//server        byte[]	     
				dos.write((byte)temps.length&0xff);
				dos.write((byte)temps.length>>8&0xff);
				dos.write(temps);
				System.out.println("printwrite send ok: " + msg);
				
				if(msg.equalsIgnoreCase("bye")){
					break;
				}
			}
			while(true);			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			closeSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			closeSocket();
		}		
	}

	/**
	 *     socket
	 *     is, os, socket
	 * socket      
	 */
	private static void closeSocket() {
		// TODO Auto-generated method stub
		if(dis != null){
			try {
				dis.close();
				dis = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		
		if(dos != null){
			try {
				dos.close();
				dos = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		
		if(socket != null){
			try {
				socket.close();
				socket = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
}


Serverコードは、関連コードのみを提供します。

public void handleRead(SelectionKey key) {
// TODO Auto-generated method stub
if (this.selectionKey != key) {
closeChannel();
this.selectionKey = key;
this.channel = (SocketChannel) key.channel();
}

try {
int ret = channel.read(inBuffer);


if (ret < 0) {
closeChannel();
}

int result = parseInput(inBuffer);

if (result < 0) {
closeChannel();
return;
}

this.lastAccessTime = System.currentTimeMillis();

} catch (IOException e) {
// TODO Auto-generated catch block
closeChannel();
// e.printStackTrace();
}

}

/**
* byteBuffer message
* logicprocess
* @param inBuffer
* @return
*/
private int parseInput(ByteBuffer inBuffer) {
// TODO Auto-generated method stub
int result = 0;
List<Message> list = server.getProtocol().parseDataInput(inBuffer, this);

if(list == null){
return -1;
}

for(int i=0; i<list.size(); i++){
server.getLogicProcess().serverProcess(list.get(i));
}

return result;
}

/**
*
*/
private void closeChannel() {
// TODO Auto-generated method stub
selectionKey.cancel();
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/* 
	 *    ByteBuffer    ,
	 *    message  
	 */
	@Override
	public List<Message> parseDataInput(ByteBuffer inBuffer, SocketSession session) {
		// TODO Auto-generated method stub
		if(inBuffer == null){
			return null;
		}
		System.out.println(inBuffer);
		
		//           tempBuf,   flip(),    underflowException
		ByteBuffer tempBuf = inBuffer.duplicate();
		inBuffer.flip();
		
		List<Message> list = new ArrayList<Message>();
		
		//          ,             
		while(inBuffer.hasRemaining()){
			if(inBuffer.remaining() < HEAD_LEN){
				break;
			}
			
			//              ,           
			byte[] data = new byte[2];
			inBuffer.get(data);
			
			//   Byte  ,   short 
			int len = ChangeTools.ByteToInt2(data, 0);
			
			//         
			data = new byte[len];
			inBuffer.get(data);
			
			//    ,       
			byte[] headData = new byte[HEAD_LEN];
			System.arraycopy(data, 0, headData, 0, HEAD_LEN);
			
			HeadModel head = parseHead(headData);
			
			
			//      
			byte[] bodyData = new byte[head.bodyLen];
			System.arraycopy(headData, 0, data, 0, headData.length);
			System.arraycopy(bodyData, 0, data, headData.length, bodyData.length);
			
			Message msg = MessageFactory.createServerMessage(session, data, headData, bodyData, head.cmdType,
					head.playerId,head.tag);
			
			if(msg == null){
				return null;
			}
			list.add(msg);			
		}
		
		//?            
		if (list.size() > 0) {
			inBuffer.compact();
			inBuffer.clear();

			inBuffer.position(inBuffer.position());
			inBuffer.limit(inBuffer.limit());
		}
		
		return list;
	}