转http://www.oschina.net/code/snippet_195686_8680
1.
public class SmsObject {
private int receiver;
private int data_type;
private int data_receiver;
private int data_sender;
private String data;
public int getReceiver(){
return receiver;
}
public int getDataType(){
return data_type;
}
public int getDataReceiver(){
return data_receiver;
}
public int getDataSender(){
return data_sender;
}
public String getData(){
return data;
}
public void setReceiver(int receiver){
this.receiver = receiver;
}
public void setDataType(int data_type){
this.data_type = data_type;
}
public void setDataReceiver(int data_receiver){
this.data_receiver = data_receiver;
}
public void setDataSender(int data_sender){
this.data_sender = data_sender;
}
public void setData(String data){
this.data = data;
}
}
2.
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
/**
* MINA Server
* @author Lazy
*/
public class Server {
private static int bindPort = 9999;
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
SocketAcceptor acceptor = new NioSocketAcceptor();
//setMinReadBufferSize(), setMaxReadBufferSize()
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
//acceptor.getManagedSessions()
//set MinaServerFilter
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
chain.addLast("codec", new ProtocolCodecFilter(new CmccCodecFactory(Charset.forName("UTF-8"))));
//set MinaServerHandler
acceptor.setHandler(new ServerHandler());
//bind port
try
{
acceptor.bind(new InetSocketAddress(bindPort));
System.out.println("Mina Server is Listing on:= " + bindPort);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
3.
import java.util.ArrayList;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class ServerHandler implements IoHandler {
//SLF4J
//private final static Logger log = LoggerFactory.getLogger(ServerHandler.class);
private static final CliLocator cli = new CliLocator();
@Override
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
// TODO Auto-generated method stub
SmsObject sms = (SmsObject) message;
//log.info("The message is [" + sms.getMessage() + "]");
/*
* other operate
System.out.println("================================================");
System.out.println("Data From : " + session.getRemoteAddress());
System.out.println("Receiver : [" + sms.getReceiver() + "]");
System.out.println("Data Type : [" + sms.getDataType() + "]");
System.out.println("Data Receiver : [" + sms.getDataReceiver() + "]");
System.out.println("Data Sender : [" + sms.getDataSender() + "]");
System.out.println("Data : [" + sms.getData() + "]");
System.out.println("================================================");
* */
//The processing of registration information
Integer i = new Integer(255);
if( i.equals(sms.getReceiver()) &&
i.equals(sms.getDataType()) &&
i.equals(sms.getDataReceiver()) &&
i.equals(sms.getDataSender())) {
cli.addCli(session, sms.getData());
System.out.println("Client : " + session.getRemoteAddress() + " DONE");
} else {
//Forwarding
ArrayList tempList = new ArrayList();
tempList = cli.getCli(sms.getReceiver());
System.out.println("tempting=======>" + session.getRemoteAddress() + " with receiver : " + sms.getReceiver());
if(tempList != null) {
//System.out.println("true");
for (IoSession session1 : tempList){
System.out.println("Send =========>" + session1.getRemoteAddress());
session1.write(sms);
}
System.out.println("================================================");
}
else System.out.println("forwarding false");
}
//Trigger the client
sms.setReceiver(i);
sms.setDataType(i);
sms.setDataReceiver(i);
sms.setDataSender(i);
sms.setData(" ");
session.write(sms);
}
@Override
public void messageSent(IoSession arg0, Object arg1) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void sessionClosed(IoSession session) throws Exception {
// TODO Auto-generated method stub
//delete the timeout address
System.out.println("Client Closed :" + session.getRemoteAddress());
cli.delCli(session);
/*
* other operate
* */
}
@Override
public void sessionCreated(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void sessionOpened(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("Come :" + session.getRemoteAddress());
/*
* other operate
* */
}
}
4.
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.mina.core.session.IoSession;
public class CliLocator {
private static HashMap> cliLocation;
public CliLocator() {
cliLocation = new HashMap>();
}
public void addCli(IoSession session, String s) {
String[] sa = s.split(" ");
ArrayList tempList = new ArrayList();
for (int i=0; i");
try {
System.out.print(cliLocation.containsKey(key));
}
catch (Exception E) {
System.out.println(E.toString());
}
*/
if(cliLocation.containsKey(key)) {
if(cliLocation.get(key) != null)
tempList = cliLocation.get(key);
} else {
tempList.add(session);
cliLocation.put(key, tempList);
continue;
}
tempList.add(session);
cliLocation.put(key, tempList);
}
}
public ArrayList getCli(int receiver) {
//System.out.println("Getting=====>" + receiver);
try{
if (cliLocation.containsKey(receiver)) {
//System.out.println("true");
return cliLocation.get(receiver);
}
else {
//System.out.println("false");
return null;
}
}
catch (Exception E) {
System.out.println(E.toString());
return null;
}
}
public void delCli(IoSession session){
ArrayList tempList = new ArrayList();
for(Integer inte : cliLocation.keySet()) {
tempList = cliLocation.get(inte);
if (tempList.contains(session)) {
tempList.remove(session);
}
}
}
}
5.
import java.nio.charset.Charset;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
public class CmccCodecFactory implements ProtocolCodecFactory{
private final CmccEncoder encoder;
private final CmccDecoder decoder;
public CmccCodecFactory(){
this(Charset.defaultCharset());
}
public CmccCodecFactory(Charset charset){
this.encoder = new CmccEncoder(charset);
this.decoder = new CmccDecoder(charset);
}
@Override
public ProtocolDecoder getDecoder(IoSession session) throws Exception{
return decoder;
}
@Override
public ProtocolEncoder getEncoder(IoSession session) throws Exception{
return encoder;
}
}
6.
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
public class CmccDecoder extends CumulativeProtocolDecoder{
private final Charset charset;
public CmccDecoder(Charset charset){
this.charset = charset;
}
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception{
IoBuffer buffer = IoBuffer.allocate(300).setAutoExpand(true);
CharsetDecoder cd = charset.newDecoder();
byte head = (byte)192;
byte end = (byte)193;
int receiver = -1, data_type = -1, data_receiver = -1, data_sender = -1;
String data="";
int matchCount = 0;
boolean flag = false;
while (in.hasRemaining()){
byte b = in.get();
buffer.put(b);
if(b == head){
buffer.flip();
buffer.clear();
matchCount = 0;
flag = true;
}else if (b == end){
if (flag){
buffer.flip();
//System.out.println(buffer);
receiver = buffer.getInt(0);
data_type = buffer.getInt(4);
data_receiver = buffer.getInt(8);
data_sender = buffer.getInt(12);
/*
System.out.println(buffer);
System.out.println(matchCount);
*/
buffer.skip(16);
data = buffer.getString(matchCount-16, cd);
/*
System.out.println("=====================================");
for (int i = 16; i < 24; i++)
System.out.println((char)buffer.get(i));
System.out.println("=====================================");
System.out.println(buffer);
*/
buffer.clear();
matchCount = 0;
break;
}
}else{
matchCount++;
}
}
SmsObject smsObject = new SmsObject();
smsObject.setReceiver(receiver);
smsObject.setDataType(data_type);
smsObject.setDataReceiver(data_receiver);
smsObject.setDataSender(data_sender);
smsObject.setData(data);
out.write(smsObject);
return false;
}
}
7.
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
public class CmccEncoder extends ProtocolEncoderAdapter{
private final Charset charset;
public CmccEncoder(Charset charset){
this.charset = charset;
}
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception{
SmsObject sms = (SmsObject)message;
CharsetEncoder ce = charset.newEncoder();
IoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true);
byte head = (byte)192;
byte end = (byte)193;
int receiver = sms.getReceiver();
int data_type = sms.getDataType();
int data_receiver = sms.getDataReceiver();
int data_sender = sms.getDataSender();
String data = sms.getData();
buffer.put(head);
buffer.putInt(receiver);
buffer.putInt(data_type);
buffer.putInt(data_receiver);
buffer.putInt(data_sender);
buffer.putString(data, ce);
buffer.put(end);
buffer.flip();
session.write(buffer);
}
}