轻轻松松写NIO(改进版)
作者:older 日期:2008-04-05 00:10:06
| nio.jar(78.1 K) | |
对已存在的NIO模块进行增强型改进,加入事件处理接口,下面提供一个参考实现的使用例子.
准备条件:接口介绍
1:服务器监听器 用来捕获远程连接或断开事件,并处理它们,接口定义如下:
1 |
/*
*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 |
/*
*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 | /*
*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 |
/*
*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 |
/*
*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 | /*
*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 次评分)
评论: 10 | 查看次数: 1170
- 共有 10 条评论
- 共有 10 条评论
发表评论
订阅
上一篇
|

文章来自:
标签: 





纸袋
数据采集器
包装盒
混凝土静力直线切
hdpe波纹管
包装盒
塑料袋
水钻排孔
国旅
pvc板
塑料袋
切割折除
墙体切割
墙锯切割
钢筋混凝土切割
弯管机
碳素
称重仪表
PDU电源分配器
纸袋
自由行
玻璃钢
pvc管
北京塑料制品
超声波探伤仪
英格索兰气动工具
DID拼接墙
液晶监视器
效果图设计
澳洲旅游
海岛游
四合院
婚纱摄影
效果图
股骨头坏死
画册印刷
不干胶印刷
手提袋印刷
涂层测厚仪
粗糙度仪
超声波测厚仪
红外测温仪
粗糙度仪
红外测温仪
红外测温仪
变压吸附制氮机
变压吸附制氧机
超声波探伤仪
板材雕刻加工
板材雕刻切割
亚克力展示架
英达生态园
小汤山温泉度假村
昌平温泉度假村
超声波测厚仪
无线上网卡
卷板机
婚纱摄影
PDU
机柜插座
北京四合院
北京四合院
剪板机
折边机
铣边机
北京效果图
效果图制作
效果图公司
北京展览公司
东空气动工具
北京SEO
炭化木
深度炭化木
巴劳木地板
航空箱
航空箱
北京航空箱
航空箱
设备箱
分水器
线号机
打号机
展厅设计
科技馆设计
博物馆设计
规划展厅设计
北京展厅设计
企业展厅设计
涂层测厚仪
超声波测厚仪
变压吸附制氮机
变压吸附制氧机
出境游
北京印刷
有机玻璃加工
石墨
wow gold
wow power leveling
warhammer online power leveling
warhammer online power leveling
oofay.us
wowmine
隔膜泵
隔膜泵
隔膜泵
磁力泵
磁力泵
磁力泵
油泵
油泵
油泵
上海展览公司
上海展览公司
上海展览公司
阀门
阀门
阀门
空调
空调
空调
胶体磨
胶体磨
胶体磨
Cosmetic surgery
Cosmetic surgery
菲律宾留学
菲律宾留学
菲律宾留学
东方医院
东方医院
东方医院
上海展览公司
阀门
油泵
qswd00
oct00nn
brogame
wow gold
wow gold
wow gold
wow power leveling
wow power leveling
wow power leveling
oofay
buy worhammer gold
东方医院
东方医院
阀门
阀门
空调
空调
上海展览公司
上海展览公司
留学新加坡
留学新加坡
英语口语
英语口语
油泵
油泵
真空泵
真空泵
胶体磨
胶体磨
中央空调
中央空调
商用中央空调
商用中央空调
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
wow gold
ghb15g
gtg10y
美女主播闪亮登场!
摇身一变,变成了一个老实巴交的牙科医生,携“妻子”范冰冰共同演绎现代女性家庭问题与女性心理健康!
范冰冰、杜汶泽首次联袂饰演夫妻,
首次将电视台“真人秀”搬上电影银幕。
美女主播手下两个助手,一个忠实,一个狡诈,后果怎样呢?
漂亮空姐“爱上”杜汶泽。
上海厂房
上海厂房
厂房出租
厂房出租
厂房租赁
厂房租赁
办公楼租赁
厂房
厂房
泵
水泵
环保设备
泵
泵
水泵
水泵
水泵
水泵
齿轮输油泵
齿轮输油泵
环保设备
cheap wow gold
runescape gold
runescape money
lotro gold
cheap lotro gold
wow gold
裏DVD
アダルト
出会い
無料 出会い
ハウスクリーニング
会社設立
FX
英会話
語学留学
台湾旅行
グアム旅行
照明
zhong