Non-Socket Based Java Server

Kill the old school: I use Java SE 5 (or java v1.5) (please don’t tell me to update, because what am I working on [which is private] I need to use this version of java).

I need help setting up a web client / server application. Every variation I searched on the internet has narrowed down to using websockets / sockets, however the java version that I use does not yet have sockets.

Does anyone have a tutorial on setting up a client / server model application that doesn't use sockets, or some code example that can point me in the right direction?

EDIT: Okay, so apparently my version of java has sockets. I will consider this more. However, now I'm just wondering how to create a Java server without using sockets?

0
source share
2 answers

You need sockets. They serve as connection endpoints . Although you can use alternatives to blocking Socketand implementations ServerSocket. NIO (New IO) uses channels. It allows non-blocking input-output:

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
               }
          }
     }
}

Using selector

Or you can use Selectorto switch between read / write / receive to allow locking only when theres nothing to do (to remove excessive CPU usage)

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);
     }
}

SelectionKeyIt supports receiving through isAcceptable(), reading through isReadable()and writing through isWritable(), so you can handle all 3 in one thread.

NIO. , , .

+3

API Socket Java 5.

- , , , .

+2

Source: https://habr.com/ru/post/1584601/


All Articles