ITeye博客

java分布式开发TCP/IP NIO无阻塞 Socket((基于消息方式实现系统间的通信) )(转)

rainyear · 2012-11-28 01:28 · NIO/SOCKET · 非技术 · Markdown

java分布式开发TCP/IP NIO无阻塞 Socket((基于消息方式实现系统间的通信) )

java 分布式 NIO socket编程 

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

 

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

 

服务端java代码:

Java代码  收藏代码

  1. package com.java.distributed.message.tcpip;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.net.ServerSocket;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.SelectionKey;
  7. import java.nio.channels.Selector;
  8. import java.nio.channels.ServerSocketChannel;
  9. 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>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))>0){
  57. readBytes +=ret;
  58. }
  59. }catch(Exception e ){
  60. readBytes=0;
  61. //ignore
  62. }finally{
  63. //反转此缓冲区。首先对当前位置设置限制,然后将该位置设置为零
  64. buffer.flip();
  65. }
  66. if(readBytes>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>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代码  收藏代码

  1. package com.java.distributed.message.tcpip;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.InetSocketAddress;
  6. import java.net.SocketAddress;
  7. import java.nio.ByteBuffer;
  8. import java.nio.channels.SelectionKey;
  9. 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>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))>0){
  55. readBytes+=ret;
  56. }
  57. }finally{
  58. buffer.flip();
  59. }
  60. if (readBytes > 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。