订阅所有JSP/Servlet的日志 订阅 | 这是最新一篇日志 上一篇 | 下一篇日志 下一篇 ]
java

轻轻松松写NIO(改进版)

附件
nio.jar(78.1 K)
 
切换到幻灯片模式

对已存在的NIO模块进行增强型改进,加入事件处理接口,下面提供一个参考实现的使用例子.

准备条件:接口介绍

1:服务器监听器 用来捕获远程连接或断开事件,并处理它们,接口定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
/*
*Copyright (c) jmin Organization. All rights reserved.
*/
package org.jmin.j2ee.kernel.net;
 
/**
 * A listener run in service side and catch connection request event from
 * client.
 *
 * @author Chris Liao
 */
 
public interface ServerListener extends NetEventListener {
 
  /**
   * When a connection requst arrives,this method will run.
   */
  public void onConnect(ConnectEvent event);
 
  /**
   * Method run after acceptance in server side.
   */
  public void onConnected(ConnectedEvent event);
 
  /**
   * Method run after remote host close connection.
   */
  public void onClosed(DisconnectEvent event);
 
}



2:连接器的监听器 它用来处理一些发生在Connection上的读写事件,如读写事件,接口如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  
/*
*Copyright (c) jmin Organization. All rights reserved.
*/
package org.jmin.j2ee.kernel.net;
 
/**
 * A communication event listener
 *
 * @author Chris Liao
 */
 
public interface NetConnectorListener extends NetEventListener {
 
  /**
   * Connection to remote host is stable
   */
  public void onConnected(ConnectedEvent event);
 
  /**
   * Read data from remote host
   */
  public void onRead(ReadEvent event);
 
  /**
   * Write data to remote host
   */
  public void onWrite(WriteEvent event);
 
  /**
   * Remote host close connection
   */
  public void onClosed(DisconnectEvent event);
 
  /**
   * When errors occur during communication
   */
  public void onError(ErrorEvent event);
 
}


下面就依据以上接口编写一个NIO参考实现例子.

第一步:编写Server Listener实现,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
*Copyright (c) jmin Organization. All rights reserved.
*/
package org.jmin.j2ee.kernel.net.nio.test;
 
import org.jmin.j2ee.kernel.net.ConnectEvent;
import org.jmin.j2ee.kernel.net.ConnectedEvent;
import org.jmin.j2ee.kernel.net.DisconnectEvent;
import org.jmin.j2ee.kernel.net.ServerListener;
import org.jmin.j2ee.kernel.net.nio.NIOConnector;
 
/**
 * A sample implementation of server listener interface and action by event.
 * This listener act on server channel.
 *
 * @author Chris Liao
 */
 
public class NIOServerListener implements ServerListener {
 
  /**
   * Method to handle a event represents request from remote host
   *
   * @param event
   */
  public void onConnect(ConnectEvent event){
 
    /**
     * cast event source to a connector
     */
    NIOConnector con = (NIOConnector)event.getSource();
 
    /**
     * print request
     */
    System.out.println("Find a connection request from: " + con.getRemoteHost());
  }
 
  /**
   * If the comming connection is accepted by server, a notification event will
   * be sent out.
   *
   * @param event
   */
  public void onConnected(ConnectedEvent event){
 
    /**
     * cast event source to a connector
     */
    NIOConnector con = (NIOConnector)event.getSource();
 
    /**
     * print request
     */
    System.out.println("Accepted a connection request from: " + con.getRemoteHost());
  }
 
  /**
   * If remote host close connection to server, a event will be sent and handled
   * by this method.
   *
   * @param event
   */
  public void onClosed(DisconnectEvent event){
 
    /**
     * cast event source to a connector
     */
    NIOConnector con = (NIOConnector)event.getSource();
 
    /**
     * print a hint message
     */
    System.out.println("Connection to host[" + con.getRemoteHost() +"] is closed from server");
  }
}
 


第二步:编写Server启动程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
 
/*
*Copyright (c) jmin Organization. All rights reserved.
*/
package org.jmin.j2ee.kernel.net.nio.test;
 
import java.io.IOException;
 
import org.jmin.j2ee.kernel.net.nio.ServerCluster;
 
/**
 * Test sample to build a socket server based on NIO and don't care more detail.
 *
 * @author chris
 */
 
public class NIOServer {
 
  /**
   * Entrance method to build a server.If get familiar with nio, it is easy to be
   * catched.
   */
  public static void main(String args[]) throws IOException {
 
    /**
     * Cluster object works as a server collection manager,some servers can be open
     * in it.Before useful operation,<method>open</method>must be invoked to create
     * a cluster instance.
     */
    ServerCluster cluster = ServerCluster.open();
 
    /**
     * Create a server listener
     */
    NIOServerListener serverListener = new NIOServerListener();
 
    /**
     * Call<method>openServer</method>to create a socket server,two necessary
     * arguments are applied here: server port and message lister class.
     *
     * We can assume that every server can handle matched messages from clients,
     * this listener class is extended from super <class>org.jmin.j2ee.kernel.Listener</class>,
     * of course,you can define sub implementation based on the class.
     */
    cluster.openServer(9988,serverListener,NIOConnectionListener.class);
 
    /**
     * Print a successful creation message on console.
     */
    System.out.println("A nio server run on port: "+ 9988);
 
    /**
     * Create a synchronized object to block the main thread and make the server kept running.
     */
    Object obj = new Object();
    try {
      synchronized (obj) {
        obj.wait();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}



第三步:编写连接监听器实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
 
/*
*Copyright (c) jmin Organization. All rights reserved.
*/
package org.jmin.j2ee.kernel.net.nio.test;
 
import org.jmin.j2ee.kernel.net.NetConnectorListener;
import org.jmin.j2ee.kernel.net.DisconnectEvent;
import org.jmin.j2ee.kernel.net.ErrorEvent;
import org.jmin.j2ee.kernel.net.ReadEvent;
import org.jmin.j2ee.kernel.net.WriteEvent;
import org.jmin.j2ee.kernel.net.ConnectedEvent;
import org.jmin.j2ee.kernel.net.nio.NIOConnector;
 
/**
 * A reference implementation of listener interface on net connector.
 * This object can handle some events from net connector, for example:
 * connection event, read event, write event and so on.
 *
 * Class instances work in client side and server side.
 *
 * @author Chris Liao
 */
 
public class NIOConnectionListener implements NetConnectorListener {
 
  /**
   * When connection to remote host is stable, a connection event will be published,
   * and catched by this method.
   */
  public void onConnected(ConnectedEvent event){
 
    /**
     * cast event source to a connector
     */
    NIOConnector con = (NIOConnector)event.getSource();
 
    /**
     * print a hint message
     */
    System.out.println("Connection to host[" + con.getRemoteHost() +"] is stable");
  }
 
  /**
   * When some data has been read from remote host,then a read event is sent out.
   * This method is used to handle the event,some detailed logic can be added here.
   */
  public void onRead(ReadEvent event) {
 
    /**
     * get a byte array from event object
     */
    byte[] data = event.getData();
 
    /**
     * cast event source to a connector
     */
    NIOConnector con = (NIOConnector)event.getSource();
 
    /**
     * print message on console
     */
    System.out.println("Read a meessage: " + new String(data));
 
    /**
     * send the data to remote, in fact the byte data will stored in temp pool
     * util ready to be sent.
     */
    con.write(data);
  }
 
  /**
   * When a connector associated with the current listener send a message to remote,
   * then publish a event as notification.
   */
  public void onWrite(WriteEvent event) {
    byte[] data = event.getData();
    System.out.println("Send a message: " + new String(data));
  }
 
  /**
   * When remote host close connection, a event will be published.
   *
   * @param event
   */
  public void onClosed(DisconnectEvent event) {
 
    /**
     * cast event source to a connector
     */
    NIOConnector con = (NIOConnector)event.getSource();
 
    /**
     * print a hint message
     */
    System.out.println("Connection to host[" + con.getRemoteHost() +"] is closed");
  }
 
  /**
   * When a error cause during communication,publish a error event
   *
   * @param event
   */
  public void onError(ErrorEvent event) {
 
    /**
     * get the cuase of error
     */
    Throwable cause = event.getCause();
 
    /**
     * Print the cause of error
     */
    System.out.println("Catch a error: " + cause.getMessage());
  }
}


该类被应用在Server与Client两端,但是根据具体情况,一般可以分别编写Server与Client端的实现,以上代码只供参考.


第四步:编写客户端的测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
*Copyright (c) jmin Organization. All rights reserved.
*/
package org.jmin.j2ee.kernel.net.nio.test;
 
import java.io.IOException;
 
import org.jmin.j2ee.kernel.net.nio.NIOConnector;
import org.jmin.j2ee.kernel.net.nio.NIOConnectorCluster;
 
/**
 * Test sample to show that how to build a nio client.
 *
 * @author Chris Liao
 */
 
public class NIOClient {
 
  /**
   * Main method to run a nio client.
   *
   */
  public static void main(String args[]) throws IOException {
 
    /**
     * Call static method from ConnectionCluster class to build its a instance,
     * this action is similar with nio.
     */
    NIOConnectorCluster cluster = NIOConnectorCluster.open();
 
    /**
     * Build a connection to remote host with threa parameters
     *
     * @arg remote host
     * @arg remote port
     * @arg message listener
     *
     * Message listener is extended from<class>org.jmin.j2ee.kernel.Listener</class>
     * You can define yourself message listeners for it.
     */
    NIOConnector con = cluster.connect("localhost", 9988,new NIOConnectionListener());
 
    /**
     * Send a message to the remote host.
     */
    con.write("I am a Chinese".getBytes());
 
    /**
     * synchronized objec to block main thread.
     */
    Object obj = new Object();
    try {
      synchronized (obj) {
        obj.wait();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}



经过上面四个步骤,我们就已经完成建立NIO通讯的全部过程,至此我们可以编译他们,并分别运行Server 与Client来看运行效果吧. 正确运行后将会在Console频繁看到 "Receive data: I am a Chinese"

如果对该通讯块细节感兴趣的话,请联系: jmin520@21cn.com.

平均得分
(0 次评分)





文章来自: 本站原创
标签: NIO 
评论: 16 | 查看次数: 2861
  • 共有 16 条评论
  • 1
  • 2
  • |
  • >>
kiki8 [2009-12-24 10:52:52]
kiki8 [2009-12-24 10:52:09]
kiki8 [2009-12-24 10:50:41]
明石焼き
ホームページ制作
駄菓子
いか焼
イギリス車
囲碁教室
居合道
工芸品
時計
産婦人科
美容整形
CFD
保険
リフォーム
結婚相談所
エステ
婚活
レンタルサーバー
探偵
税理士
不動産会社
看護師求人
インプラント
システム開発
求人
SEO対策
風俗
風俗求人
FX
人気
転職
歯医者
自動車保険
高収入
証券会社
高校
ラーメン
クレジットカード
太陽光発電
コスメ
オンラインゲーム
企業
化粧品
就職
大学
ホームページ制作
オール電化
ホテル
歯医者
引越
歯医者
エステ
口コミ
探偵
結婚相談所
美容整形
エステ
病院
化粧品
コスメ
産婦人科
ダイエット
新築 静岡
原宿 ウェディング
広島 新築
広島 土地
広島 住宅
岡山 マンション
結婚情報サービス
明石焼き
ホームページ制作
駄菓子
いか焼
イギリス車
囲碁教室
居合道
工芸品
時計
産婦人科
美容整形
CFD
保険
リフォーム
結婚相談所
エステ
婚活
レンタルサーバー
探偵
税理士
不動産会社
看護師求人
インプラント
システム開発
求人
SEO対策
風俗
風俗求人
FX
人気
転職
歯医者
自動車保険
高収入
証券会社
高校
ラーメン
クレジットカード
太陽光発電
コスメ
オンラインゲーム
企業
化粧品
就職
大学
ホームページ制作
オール電化
ホテル
歯医者
引越
歯医者
エステ
口コミ
探偵
結婚相談所
美容整形
エステ
病院
化粧品
コスメ
産婦人科
ダイエット
新築 静岡
原宿 ウェディング
広島 新築
広島 土地
広島 住宅
岡山 マンション
結婚情報サービス
kiki8 [2009-12-24 10:47:17]
kiki8 [2009-12-24 10:46:42]
tutu11 [2009-11-30 19:21:04]
游客 [2008-11-28 20:04:33]
如果有人需要它的详细文挡,那可以多写点
游客 [2008-11-26 17:27:58]
这方面的文档好像没有?那如何推广开来?
游客 [2008-11-19 15:06:40]
游客 [2008-11-11 09:08:38]
游客 [2008-10-22 14:05:18]
游客 [2008-10-15 09:57:16]
范冰冰当上了“问题妈妈”?
ghb15g
gtg10y
美女主播闪亮登场!
摇身一变,变成了一个老实巴交的牙科医生,携“妻子”范冰冰共同演绎现代女性家庭问题与女性心理健康!
范冰冰、杜汶泽首次联袂饰演夫妻,
首次将电视台“真人秀”搬上电影银幕。
美女主播手下两个助手,一个忠实,一个狡诈,后果怎样呢?
漂亮空姐“爱上”杜汶泽。

上海厂房
上海厂房
厂房出租
厂房出租
厂房租赁
厂房租赁
办公楼租赁
厂房
厂房

水泵
环保设备


水泵
水泵
水泵
水泵
齿轮输油泵
齿轮输油泵
环保设备
游客 [2008-09-16 17:01:08]
游客 [2008-04-15 12:32:15]
写的很好!
zhong
游客 [2008-04-05 18:35:18]
写得太好了!
  • 共有 16 条评论
  • 1
  • 2
  • |
  • >>
发表评论
昵 称:  登录
内 容:
选 项:
字数限制 1000 字 | UBB代码 开启 | [img]标签 开启