Path: blob/master/test/jdk/java/nio/channels/Selector/ByteServer.java
41153 views
/*1* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* Utility class for tests. A simple "in-thread" server to accept connections25* and write bytes.26* @author kladko27*/2829import java.net.Socket;30import java.net.ServerSocket;31import java.net.SocketAddress;32import java.net.InetSocketAddress;33import java.io.IOException;34import java.io.Closeable;3536public class ByteServer implements Closeable {3738private final ServerSocket ss;39private Socket s;4041ByteServer() throws IOException {42this.ss = new ServerSocket(0);43}4445SocketAddress address() {46return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort());47}4849void acceptConnection() throws IOException {50if (s != null)51throw new IllegalStateException("already connected");52this.s = ss.accept();53}5455void closeConnection() throws IOException {56Socket s = this.s;57if (s != null) {58this.s = null;59s.close();60}61}6263void write(int count) throws IOException {64if (s == null)65throw new IllegalStateException("no connection");66s.getOutputStream().write(new byte[count]);67}6869public void close() throws IOException {70if (s != null)71s.close();72ss.close();73}74}757677