這些方法可以幫助你在不使用mina filter的情況下進行轉碼!如果你手機上直接用socket的話,mina server就不能用filter。所以說下面的方法對你來說很有用的。你可以把你的代碼弄出來大家看看。那樣會更好的幫你找出問題的所在
/**
* 將byte[]轉換成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轉換成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轉換成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轉換成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轉換成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發給服務器端
服務器端:如何得到數據呢?
acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
//創建接收數據的過濾器
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//設定這個過濾器將一行一行(/r/n)的讀取數據
chain.addLast("myChin",new ProtocolCodecFilter(new TextLineCodecFactory()));
chain.addLast("ddd", new StreamWriteFilter());
acceptor.setHandler(new TimeServerHandler(this));//指定業務邏輯處理器
acceptor.setDefaultLocalAddress(new InetSocketAddress(PORT));//設置端口號
try {
//設置端口號
acceptor.bind(); //啟動監聽
} catch (IOException ex) { }
如果設置:chain.addLast("myChin",new ProtocolCodecFilter(new TextLineCodecFactory())); TimeServerHandler根本就執行不到:messageReceived,
如果設置: chain.addLast("ddd", new StreamWriteFilter()); TimeServerHandler的messageReceived能得到數據:message.toString()?。健?HeapBuffer[pos=0 lim=8 cap=2048: 00 06 31 31 31 31 31 31]"