下面通過簡單的例子來學習mina的使用。首先建立服務端,工程正使用了3個jar包
<a href="http://blog.51cto.com/attachment/201212/115305621.png" target="_blank"></a>
看代碼:
public class HelloMina {
private static final int PORT = 9125;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//建立一個非阻塞的server端Socket ,用NIO
IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
// 設定伺服器端的消息處理器
acceptor.setHandler( new MinaServerHandler() );
acceptor.getSessionConfig().setReadBufferSize( 2048 );
acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
// 伺服器端綁定的端口 啟動服務
acceptor.bind( new InetSocketAddress(PORT) );
}
}
HelloMina的處理器:
/**
* HelloMina的處理邏輯
* @author zhangxy
*/
class MinaServerHandler extends IoHandlerAdapter {
@Override
public void exceptionCaught( IoSession session, Throwable cause ) throws Exception{
cause.printStackTrace();
session.close();
@Override
public void messageReceived( IoSession session, Object message ) throws Exception
{
String str = message.toString();
if( str.trim().equalsIgnoreCase("quit") ) {
session.close();
return;
}
System.err.println("收到用戶端發來的消息::"+str);
StringBuilder buf = new StringBuilder(str.length());
for (int i = str.length() - 1; i >= 0; i--) {
buf.append(str.charAt(i));
}
// and write it back.
session.write(buf.toString());
public void sessionIdle( IoSession session, IdleStatus status ) throws Exception{
System.out.println( "IDLE " + session.getIdleCount( status ));
public void messageSent(IoSession session, Object message)
throws Exception {
// TODO Auto-generated method stub
super.messageSent(session, message);
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System.out.println( "session closed");
public void sessionCreated(IoSession session) throws Exception {
super.sessionCreated(session);
System.out.println( "session create");
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
System.out.println( "session opened");
下面是Client代碼,Client沒有使用NIO,使用的普通socket實作:
public class HelloMinaClient {
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
public HelloMinaClient() throws IOException {
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
HelloMinaClient minaClient = new HelloMinaClient();
minaClient.minaClient();
* 發送消息
* @param out
public void sendMessage(Socket s) {
try {
out = new DataOutputStream(s.getOutputStream());
out.writeBytes("mina\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void receiveMessage(Socket s) {
in = new DataInputStream(s.getInputStream());
System.err.println("收到服務端發來的消息::"+in.readLine());
} catch (Exception e) {
public void minaClient() throws Exception {
while (true) {
try {
socket = new Socket("192.168.21.121", 9124);
sendMessage(socket);
receiveMessage(socket);
out.close();
in.close();
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
}finally {
try{
if(socket!=null)socket.close(); //斷開連接配接
}catch (IOException e) {e.printStackTrace();}
}
SOCKET作為短連接配接,即收發消息後SOCKET斷開一次,線程過5秒又建立連接配接收發消息。
/**
* @author 張興業
* android開發進階群:278401545
* http://xyzlmn.blog.51cto.com/
*/
本文轉自xyz_lmn51CTO部落格,原文連結:<b>http://blog.51cto.com/xyzlmn/1089948</b>,如需轉載請自行聯系原作者