ByteServer.java revision 3261:a06412e13bf7
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 24/** 25 * 26 * Utility class for tests. A simple server, which waits for a connection, 27 * writes out n bytes and waits. 28 * @author kladko 29 */ 30 31import java.net.Socket; 32import java.net.ServerSocket; 33 34public class ByteServer { 35 36 public static final String LOCALHOST = "localhost"; 37 private int bytecount; 38 private Socket socket; 39 private ServerSocket serversocket; 40 private Thread serverthread; 41 volatile Exception savedException; 42 43 public ByteServer(int bytecount) throws Exception{ 44 this.bytecount = bytecount; 45 serversocket = new ServerSocket(0); 46 } 47 48 public int port() { 49 return serversocket.getLocalPort(); 50 } 51 52 public void start() { 53 serverthread = new Thread() { 54 public void run() { 55 try { 56 socket = serversocket.accept(); 57 socket.getOutputStream().write(new byte[bytecount]); 58 socket.getOutputStream().flush(); 59 } catch (Exception e) { 60 System.err.println("Exception in ByteServer: " + e); 61 System.exit(1); 62 } 63 } 64 }; 65 serverthread.start(); 66 } 67 68 public void exit() throws Exception { 69 serverthread.join(); 70 socket.close(); 71 serversocket.close(); 72 } 73} 74