---
title: "java分布式开发TCP/IP NIO无阻塞 Socket（(基于消息方式实现系统间的通信) ）(转)"
author: "rainyear"
date: "2012-11-28T01:28:21Z"
tags: []
categories: ["非技术"]
slug: "java-tcp-ip-nio-socket"
draft: false
lastmod: "2012-11-28T01:28:21Z"
id: 1736330
url: "https://rainyear.iteye.com/blog/1736330"
---

### [java分布式开发TCP/IP NIO无阻塞 Socket（(基于消息方式实现系统间的通信) ）](http://mars914.iteye.com/blog/1238353)

- **博客分类：**
- [java 网络编程](http://mars914.iteye.com/category/187630)

[java 分布式 NIO socket编程](http://www.iteye.com/blogs/tag/java%20%E5%88%86%E5%B8%83%E5%BC%8F%20NIO%20socket%E7%BC%96%E7%A8%8B) 

在java中可以基于java.nio.channels中的Channel和Selector的相关类来实现TCP/IP+NIO方式的系统间通信。

 

用于系统间通信依靠SocketChannel和ServerSocketChannel，SocketChannel用于建立连接，监听事件及操作读写，ServerSocketChannel用于监听端口及监听连接事件，可通过Selector来获取是否有要处理的事件。

 

服务端java代码：

Java代码  [![收藏代码](http://mars914.iteye.com/images/icon_star.png)](http://mars914.iteye.com/blog/1238353 "收藏这段代码")

01. package com.java.distributed.message.tcpip;
02. import java.io.IOException;
03. import java.net.InetSocketAddress;
04. import java.net.ServerSocket;
05. import java.nio.ByteBuffer;
06. import java.nio.channels.SelectionKey;
07. import java.nio.channels.Selector;
08. import java.nio.channels.ServerSocketChannel;
09. import java.nio.channels.SocketChannel;
10. import java.nio.charset.Charset;
11. public class NIOServer {
12. /\**
13. * @param args
14. * @throws IOException
15. \*/
16. public static void main(String\[] args) throws IOException {
17. int port =7889;
18. //打开选择器
19. Selector selector=Selector.open();
20. //打开服务器套接字通道
21. ServerSocketChannel ssc=ServerSocketChannel.open();
22. //检索与此通道关联的服务器套接字
23. ServerSocket serverSocket=ssc.socket();
24. //将 ServerSocket 绑定到特定地址（IP 地址和端口号）
25. serverSocket.bind(new InetSocketAddress(port));
26. System.out.println("server listen on port:"+port);
27. //调整通道的阻塞模式
28. ssc.configureBlocking(false);
29. //向给定的选择器注册此通道，返回一个选择键。SelectionKey.OP\_ACCEPT--用于套接字接受操作的操作集位
30. ssc.register(selector, SelectionKey.OP\_ACCEPT);
31. while(true){
32. //timeout:为正，则在等待某个通道准备就绪时最多阻塞 timeout 毫秒；如果为零，则无限期地阻塞；必须为非负数
33. int nKeys=selector.select(1000);
34. if(nKeys&gt;0){
35. for(SelectionKey key:selector.selectedKeys()){
36. /\*测试此键的通道是否已准备好接受新的套接字连接--
37. * 如果此键的通道不支持套接字接受操作，则此方法始终返回 false
38. * \*/
39. if(key.isAcceptable()){
40. ServerSocketChannel server=(ServerSocketChannel) key.channel();
41. SocketChannel sc=server.accept();
42. if(sc==null){
43. continue;
44. }
45. sc.configureBlocking(false);
46. sc.register(selector, SelectionKey.OP\_READ);
47. }else if(key.isReadable()){
48. //分配一个新的字节缓冲区
49. ByteBuffer buffer=ByteBuffer.allocate(1024);
50. SocketChannel sc=(SocketChannel) key.channel();
51. int readBytes=0;
52. String message=null;
53. try{
54. int ret;
55. try{
56. while((ret=sc.read(buffer))&gt;0){
57. readBytes +=ret;
58. }
59. }catch(Exception e ){
60. readBytes=0;
61. //ignore
62. }finally{
63. //反转此缓冲区。首先对当前位置设置限制，然后将该位置设置为零
64. buffer.flip();
65. }
66. if(readBytes&gt;0){
67. message=Charset.forName("UTF-8").decode(buffer).toString();
68. buffer=null;
69. }
70. }finally{
71. if(buffer!=null)
72. buffer.clear();
73. }
74. if(readBytes&gt;0){
75. System.out.println("message from client:"+message);
76. if("quit".equalsIgnoreCase(message.trim())){
77. sc.close();
78. selector.close();
79. System.out.println("Server has been shutdown!");
80. System.exit(0);
81. }
82. String outMessage="server response:"+message;
83. sc.write(Charset.forName("UTF-8").encode(outMessage));
84. }
85. }
86. }
87. selector.selectedKeys().clear();
88. }
89. }
90. }
91. }

 

 

客户端java代码：

Java代码  [![收藏代码](http://mars914.iteye.com/images/icon_star.png)](http://mars914.iteye.com/blog/1238353 "收藏这段代码")

01. package com.java.distributed.message.tcpip;
02. import java.io.BufferedReader;
03. import java.io.IOException;
04. import java.io.InputStreamReader;
05. import java.net.InetSocketAddress;
06. import java.net.SocketAddress;
07. import java.nio.ByteBuffer;
08. import java.nio.channels.SelectionKey;
09. import java.nio.channels.Selector;
10. import java.nio.channels.SocketChannel;
11. import java.nio.charset.Charset;
12. public class NIOClient {
13. /\**
14. * @param args
15. * @throws IOException
16. \*/
17. public static void main(String\[] args) throws IOException {
18. int port =7889;
19. SocketChannel channel=SocketChannel.open();
20. channel.configureBlocking(false);
21. SocketAddress target=new InetSocketAddress("127.0.0.1",port);
22. channel.connect(target);
23. Selector selector=Selector.open();
24. //用于套接字连接操作的操作集位
25. channel.register(selector, SelectionKey.OP\_CONNECT);
26. BufferedReader systemIn=new BufferedReader(new InputStreamReader(System.in));
27. while(true){
28. if(channel.isConnected()){
29. String command=systemIn.readLine();
30. channel.write(Charset.forName("UTF-8").encode(command));
31. if(command==null||"quit".equalsIgnoreCase(command.trim())){
32. systemIn.close();
33. channel.close();
34. selector.close();
35. System.out.println("Client quit !");
36. System.exit(0);
37. }
38. }
39. int nKeys=selector.select(1000);
40. if(nKeys&gt;0){
41. for(SelectionKey key:selector.selectedKeys()){
42. if(key.isConnectable()){
43. SocketChannel sc=(SocketChannel) key.channel();
44. sc.configureBlocking(false);
45. sc.register(selector, SelectionKey.OP\_READ);
46. sc.finishConnect();
47. }else if(key.isReadable()){
48. ByteBuffer buffer=ByteBuffer.allocate(1024);
49. SocketChannel sc=(SocketChannel) key.channel();
50. int readBytes=0;
51. try{
52. int ret=0;
53. try{
54. while((ret=sc.read(buffer))&gt;0){
55. readBytes+=ret;
56. }
57. }finally{
58. buffer.flip();
59. }
60. if (readBytes &gt; 0) {
61. System.out.println(Charset.forName("UTF-8")
62. .decode(buffer).toString());
63. buffer = null;
64. }
65. }finally {
66. if (buffer != null) {
67. buffer.clear();
68. }
69. }
70. }
71. }
72. selector.selectedKeys().clear();
73. }
74. }
75. }
76. }