java socket 多線程通訊 使用mina作為服務端

來源:互聯網
上載者:User

標籤:nas   ext   last   object   err   actor   net   toc   時間長度   

用戶端代碼不變,參照 http://www.cnblogs.com/Westfalen/p/6251473.html

服務端代碼如下:

import java.io.IOException;import java.net.InetSocketAddress;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;/** * 使用mina作為伺服器進行socket通訊 *  * 需要jar包: mina-core-2.0.16.jar, slf4j-api-1.7.21.jar * jar包 : http://mina.apache.org/downloads-mina.html  * */public class MinaServer {    public static void main(String[] args) {        try {            // 4步操作            // 1.建立 NioSocketAcceptor 案例對象            NioSocketAcceptor acceptor = new NioSocketAcceptor();            // 2.設定訊息處理對象            acceptor.setHandler(new MyServerHandler());            // 3.設定訊息解碼器            acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));            // acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 3);            // //設定idle時間長度            // 4.綁定連接埠開啟服務            acceptor.bind(new InetSocketAddress(9999));        } catch (IOException e) {            e.printStackTrace();        }    }}/** * 專門處理訊息的類,實現網路連接和訊息處理的解耦 */class MyServerHandler extends IoHandlerAdapter {    /** 異常時候的處理 */    @Override    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {        System.out.println("exceptionCaught");    }    /** 收到訊息 */    @Override    public void messageReceived(IoSession session, Object message) throws Exception {        System.out.println("messageReceived " + message);        // session.write("reply " + message); //收到訊息就馬上把訊息回送給用戶端    }    /** 發送訊息 */    @Override    public void messageSent(IoSession session, Object message) throws Exception {        System.out.println("messageSent " + message);    }    /** 通訊閑置時候的處理 */    @Override    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {        System.out.println("sessionIdle");    }}

 

java socket 多線程通訊 使用mina作為服務端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.