這些方法可以幫助你在不使用mina filter的情況下進行轉(zhuǎn)碼!如果你手機上直接用socket的話,mina server就不能用filter。所以說下面的方法對你來說很有用的。你可以把你的代碼弄出來大家看看。那樣會更好的幫你找出問題的所在
/**
* 將byte[]轉(zhuǎn)換成string
* @param butBuffer
*/
public static String byteToString(byte [] b)
{
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < b.length; i++)
{
stringBuffer.append((char) b [i]);
}
return stringBuffer.toString();
}
/**
* 將bytebuffer轉(zhuǎn)換成string
* @param str
*/
public static IoBuffer stringToIoBuffer(String str)
{
byte bt[] = str.getBytes();
IoBuffer ioBuffer = IoBuffer.allocate(bt.length);
ioBuffer.put(bt, 0, bt.length);
ioBuffer.flip();
return ioBuffer;
}
/**
* 將IoBuffer轉(zhuǎn)換成string
* @param str
*/
public static IoBuffer byteToIoBuffer(byte [] bt,int length)
{
IoBuffer ioBuffer = IoBuffer.allocate(length);
ioBuffer.put(bt, 0, length);
ioBuffer.flip();
return ioBuffer;
}
/**
* 將IoBuffer轉(zhuǎn)換成byte
* @param str
*/
public static byte [] ioBufferToByte(Object message)
{
if (!(message instanceof IoBuffer))
{
return null;
}
IoBuffer ioBuffer = (IoBuffer)message;
byte[] b = new byte[ioBuffer.limit()];
ioBuffer.get(b);
return b;
}
/**
* 將IoBuffer轉(zhuǎn)換成string
* @param butBuffer
*/
public static String ioBufferToString(Object message)
{
if (!(message instanceof IoBuffer))
{
return "";
}
IoBuffer ioBuffer = (IoBuffer) message;
byte[] b = new byte [ioBuffer.limit()];
ioBuffer.get(b);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < b.length; i++)
{
stringBuffer.append((char) b [i]);
}
return stringBuffer.toString();
}
手機端:
try {
socket = (SocketConnection) Connector.open("socket://127.0.0.1:9123");
dis = socket.openDataInputStream();
dos = socket.openDataOutputStream();
String str = "111111";
dos.writeUTF(str);
} catch (IOException ex) {
ex.printStackTrace();
}
將字符串:111111發(fā)給服務(wù)器端
服務(wù)器端:如何得到數(shù)據(jù)呢?
acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
//創(chuàng)建接收數(shù)據(jù)的過濾器
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//設(shè)定這個過濾器將一行一行(/r/n)的讀取數(shù)據(jù)
chain.addLast("myChin",new ProtocolCodecFilter(new TextLineCodecFactory()));
chain.addLast("ddd", new StreamWriteFilter());
acceptor.setHandler(new TimeServerHandler(this));//指定業(yè)務(wù)邏輯處理器
acceptor.setDefaultLocalAddress(new InetSocketAddress(PORT));//設(shè)置端口號
try {
//設(shè)置端口號
acceptor.bind(); //啟動監(jiān)聽
} catch (IOException ex) { }
如果設(shè)置:chain.addLast("myChin",new ProtocolCodecFilter(new TextLineCodecFactory())); TimeServerHandler根本就執(zhí)行不到:messageReceived,
如果設(shè)置: chain.addLast("ddd", new StreamWriteFilter()); TimeServerHandler的messageReceived能得到數(shù)據(jù):message.toString() = "HeapBuffer[pos=0 lim=8 cap=2048: 00 06 31 31 31 31 31 31]"