基于非套接字的Java Server

时间:2014-07-07 17:56:18

标签: java webserver

踢它老学校:我正在使用Java SE 5(或java v1.5)(请不要告诉我升级,因为我正在处理[私有]我需要使用这个版本的java)。

我需要帮助设置Web客户端/服务器应用程序。我在网上寻找的每个变种都缩小到使用websockets / socket,但是我使用的java版本还没有套接字。

有没有人有一个教程来设置不使用套接字的客户端/服务器模型应用程序,或者一些可以指向正确方向的示例代码?

编辑: 好吧,显然我的java版本确实有套接字。我会再研究一下。但是,现在我只是好奇,如何创建一个不使用套接字的java服务器?

2 个答案:

答案 0 :(得分:3)

你需要套接字。 They serve as the end-points to the connection。但是,您可以使用阻止SocketServerSocket实现的替代方法。

NIO(新IO)使用频道。它允许非阻塞I / O:

class Server {
     public static void main(String[] args) throws Exception {
          ServerSocketChannel ssc = ServerSocketChannel.open();
          ssc.configureBlocking(false);

          while(true) {
               SocketChannel sc = ssc.accept();

               if(sc != null) {
                    //handle channel
               }
          }
     }
}

使用选择器(可选,但建议使用)

您可以使用Selector在读取/写入/接受之间切换,以便仅在无法执行任何操作时阻止阻塞(以消除多余的CPU使用情况)

class Server {
     private static Selector selector;
     public static void main(String[] args) throws Exception {
          ServerSocketChannel ssc = ServerSocketChannel.open();
          ssc.configureBlocking(false);
          Selector selector = Selector.open();
          ssc.register(selector, SelectionKey.OP_ACCEPT);

          while(true) {
               selector.select();

               while(selector.iterator().hasNext()) {
                    SelectionKey key = selector.iterator().next();

                    if(key.isAcceptable()) {
                         accept(key);
                    }
               }
          }
     }

     private static void accept(SelectionKey key) throws Exception {
          ServerSocketChannel channel = (ServerSocketChannel) key.channel();
          SocketChannel sc = channel.accept();
          sc.register(selector, OP_READ);
     }
}

SelectionKey支持通过isAcceptable()接受,通过isReadable()阅读并通过isWritable()撰写,这样您就可以在同一个帖子上处理所有3个。

这是使用NIO接受连接的基本示例。我强烈建议再深入研究一下,以便更好地了解事情的运作方式。

答案 1 :(得分:2)

以下是来自Java 5的课程Socket的API文档。

套接字是网络通信的基本抽象,你很难找到一个不支持它们的操作系统,更不用说高级编程语言了。