View Javadoc
1   /*
2    * junixsocket
3    *
4    * Copyright 2009-2024 Christian Kohlschütter
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.newsclub.net.unix.demo.mina;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.nio.charset.StandardCharsets;
23  
24  import org.apache.mina.core.service.IoAcceptor;
25  import org.apache.mina.core.session.IdleStatus;
26  import org.apache.mina.filter.codec.ProtocolCodecFilter;
27  import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
28  import org.apache.mina.filter.logging.LoggingFilter;
29  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
30  import org.newsclub.net.unix.AFUNIXSelectorProvider;
31  import org.newsclub.net.unix.AFUNIXSocketAddress;
32  
33  /**
34   * Apache Mina-based Time server, modified to use junixsocket.
35   *
36   * Based on example code from
37   * <a href="https://mina.apache.org/mina-project/userguide/ch2-basics/ch2.2-sample-tcp-server.html">
38   * Apache Mina user guide, chapter 2.2 — Sample TCP Server</a>
39   */
40  public class MinaTimeServer {
41    public static void main(String[] args) throws IOException {
42      int processorCount = Runtime.getRuntime().availableProcessors() + 1;
43  
44      // IoAcceptor acceptor = new NioSocketAcceptor(processorCount); // from original example code
45      IoAcceptor acceptor = new NioSocketAcceptor(processorCount, AFUNIXSelectorProvider.provider());
46      // IoAcceptor acceptor = new NioSocketAcceptor(processorCount,
47      // AFTIPCSelectorProvider.provider());
48  
49      acceptor.getFilterChain().addLast("logger", new LoggingFilter());
50      acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(
51          StandardCharsets.UTF_8)));
52      acceptor.setHandler(new TimeServerHandler());
53      acceptor.getSessionConfig().setReadBufferSize(2048);
54      acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
55  
56      // acceptor.bind( new InetSocketAddress(PORT) ); // from original example code
57      AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(new File("/tmp/minatime"));
58      acceptor.bind(addr);
59      // acceptor.bind(AFTIPCSocketAddress.ofService(Scope.SCOPE_CLUSTER, 128, 1));
60      System.out.println("Bound to " + addr);
61    }
62  }