1 /*
   2  * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /**
  25  * Utility class for tests. A simple "in-thread" server to accept connections
  26  * and write bytes.
  27  */
  28 
  29 import java.net.Socket;
  30 import java.net.ServerSocket;
  31 import java.net.SocketAddress;
  32 import java.net.InetSocketAddress;
  33 import java.net.InetAddress;
  34 import java.io.IOException;
  35 import java.io.Closeable;
  36 import jdk.net.Sockets;
  37 
  38 public class ByteServer implements Closeable {
  39 
  40     private final ServerSocket ss;
  41     private Socket s;
  42 
  43     ByteServer() throws IOException {
  44         ServerSocket ss = Sockets.openRdmaServerSocket();
  45         ss.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
  46         this.ss = ss;
  47     }
  48 
  49     SocketAddress address() {
  50         return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort());
  51     }
  52 
  53     void acceptConnection() throws IOException {
  54         if (s != null)
  55             throw new IllegalStateException("already connected");
  56         this.s = ss.accept();
  57     }
  58 
  59     void closeConnection() throws IOException {
  60         Socket s = this.s;
  61         if (s != null) {
  62             this.s = null;
  63             s.close();
  64         }
  65     }
  66 
  67     void write(int count) throws IOException {
  68         if (s == null)
  69             throw new IllegalStateException("no connection");
  70         s.getOutputStream().write(new byte[count]);
  71     }
  72 
  73     public void close() throws IOException {
  74         if (s != null)
  75             s.close();
  76         ss.close();
  77     }
  78 }