This Domain(Admin5.com) is for Sale:

使用Java NIO提高服务端程序的性能

时间:2007-12-27  来源:不详  作者:林子

61
62 }
63
64 public void startWork()throws Exception

织梦好,好织梦

65
66 {
67 while (true) {
68
69 int n = selector.select();//获得IO预备就绪的channel数量
70
71 if (n == 0) {
72 continue; // 没有channel预备就绪,继续执行
73 }
74
75 // 用一个iterator返回Selector的selectedkeys
76 Iterator it = selector.selectedKeys().iterator();
77
78 // 处理每一个SelectionKey
79 while (it.hasNext()) {
80 SelectionKey key = (SelectionKey) it.next();
81
82 // 判定是否有新的连接到达
83 if (key.isAcceptable()) {
84           //返回SelectionKey的ServerSocketChannel
85 ServerSocketChannel server =
(ServerSocketChannel) key.channel();
86 SocketChannel channel = server.accept();
87
88 registerChannel (selector, channel,
89 SelectionKey.OP_READ);
90
91 doWork (channel);
92 }
93
94 // 判定是否有数据在此channel里需要读取
95 if (key.isReadable()) {
96
97 processData (key);
98
99 }
100
101 //删除 selectedkeys
102 it.remove();
103 }
104 }
105 }
106 protected void registerChannel (Selector selector, 织梦内容管理系统
107 SelectableChannel channel, int ops)
108 throws Exception
109 { 内容来自dedecms

110 if (channel == null) {
111 return;
112 }
113
114
115 channel.configureBlocking (false);
116
117 channel.register (selector, ops);
118 }
119
120 //处理接收的数据
121 protected void processData (SelectionKey key)
122 throws Exception
123 {
124
125
126 SocketChannel socketChannel = (SocketChannel) key.channel();
127 int count;
128
129 buffer.clear(); // 清空buffer
130
131 // 读取所有的数据
132 while ((count = socketChannel.read (buffer)) > 0) {
133 buffer.flip();
134
135 // send the data, don′t assume it goes all at once
136 while (buffer.hasRemaining())
137 {
138 //假如收到回车键,则在返回的字符前增加[echo]$字样
139 if(buffer.get()==(char)13)
140 {
141 buffer.clear();
142 buffer.put("[echo]___FCKpd___0quot;.getBytes());
143 buffer.flip();
144
145 }
146 socketChannel.write (buffer);//在Socket里写数据
147 }
148
149 buffer.clear(); // 清空buffer
150 }
151
152 if (count < 0) {

内容来自dedecms


153 // count<0,说明已经读取完毕
154 socketChannel.close(); dedecms.com

155 }
156 }
157
158
159 private void doWork (SocketChannel channel)throws Exception
160 {
161 buffer.clear();
162 buffer.put ("
Hello,I am working,please input some thing,and i will echo to you!
[echo]
___FCKpd___0quot;.getBytes());
163 buffer.flip();
164 channel.write (buffer);
165 }
166
167 } 织梦好,好织梦

使用:运行此程序,然后在控制台输入命令telnet localhost 23。

本文来自织梦

看完这篇,您有何感觉呢?

文章评论

共有位Admini5网友发表了评论 查看完整内容

24小时热门信息