码迷,mamicode.com
首页 > 编程语言 > 详细

java nio网络编程服务篇入门

时间:2016-09-13 07:57:44      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

服务端写完了,现在写一个客户端,对于客户端,我考虑使用nio或阻塞socket都可以。

使用nio的客户端:

 1 /**
 2  * 初始化网络连接
 3  */
 4 public void run() {
 5 
 6     // 开启网络连接
 7     try {
 8         channel = SocketUtils.connect("127.0.0.1",8080);
 9         selector = Selector.open();
10         channel.register(selector, SelectionKey.OP_CONNECT);
11         while(running) {
12             selector.select();
13             Iterator ite = selector.selectedKeys().iterator();
14             while (ite.hasNext()) {
15                 SelectionKey key = (SelectionKey) ite.next();
16                 ite.remove();
17                 readData(key);
18             }
19         }
20     } catch (Throwable e) {
21         logger.error(" socket or other fail!",e);
22     } finally {
23         // 关闭channel
24         if (channel != null) {
25             try {
26                 channel.close();
27             } catch (IOException e) {
28                 e.printStackTrace();
29             }
30         }
31         // 关闭selector
32         if (selector != null) {
33             try {
34                 selector.close();
35             } catch (IOException e) {
36                 e.printStackTrace();
37             }
38         }
39     }
40 }

读取数据方式和服务端一样,就不写了。

 

下面是阻塞socket方式:

 1 public void run(){
 2     byte[] buffer = new byte[512];
 3     running = true;
 4     while(running) {
 5         try {
 6             socket = new Socket("127.0.0.1", 8080);
 7             InputStream inputStream = socket.getInputStream();
 8             OutputStream outputStream = socket.getOutputStream();
 9             handleConnectListener(ConnectListener.ConnectStatus.connected);
10             // 读取数据
11             int bufferCount = -1;
12             ByteBuffer byteBuffer = ByteBuffer.allocate(buffer.length*2);
13             messageHandler.initByteBufferSize(byteBuffer.capacity());
14             while ((bufferCount = inputStream.read(buffer))>=0){
15                 byteBuffer.put(buffer,0,bufferCount);
16                 // TODO 解析 
17             }
18         } catch (Exception e) {
19             e.printStackTrace();
20         }
21     }
22 }

客户端在连接时,是继承Thread的,调用时记得start()。

虽然第二个实例没有使用nio,但使用bytebuffer,这个东西还是很好用的。

 

java nio网络编程服务篇入门

标签:

原文地址:http://www.cnblogs.com/sunzuoquan/p/5867095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!