• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2002, 2010, 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 package test.java.nio.channels.Selector;
24 
25 /**
26  * Utility class for tests. A simple "in-thread" server to accept connections
27  * and write bytes.
28  * @author kladko
29  */
30 
31 import java.net.Socket;
32 import java.net.ServerSocket;
33 import java.net.SocketAddress;
34 import java.net.InetSocketAddress;
35 import java.io.IOException;
36 import java.io.Closeable;
37 
38 public class ByteServer implements Closeable {
39 
40     private final ServerSocket ss;
41     private Socket s;
42 
ByteServer()43     ByteServer() throws IOException {
44         this.ss = new ServerSocket(0);
45     }
46 
address()47     SocketAddress address() {
48         return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort());
49     }
50 
acceptConnection()51     void acceptConnection() throws IOException {
52         if (s != null)
53             throw new IllegalStateException("already connected");
54         this.s = ss.accept();
55     }
56 
closeConnection()57     void closeConnection() throws IOException {
58         Socket s = this.s;
59         if (s != null) {
60             this.s = null;
61             s.close();
62         }
63     }
64 
write(int count)65     void write(int count) throws IOException {
66         if (s == null)
67             throw new IllegalStateException("no connection");
68         s.getOutputStream().write(new byte[count]);
69     }
70 
close()71     public void close() throws IOException {
72         if (s != null)
73             s.close();
74         ss.close();
75     }
76 }