ReuseBuf.java revision 6073:cea72c2bf071
1/* 2 * Copyright (c) 2001, 2012, 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 * @test 26 * 27 * @bug 4424096 28 * 29 * @summary DatagramPacket spec needs clarification (reuse buf) 30 */ 31import java.net.*; 32 33public class ReuseBuf { 34 static String msgs[] = {"Hello World", "Java", "Good Bye"}; 35 static int port; 36 37 static class ServerThread extends Thread{ 38 DatagramSocket ds; 39 public ServerThread() { 40 try { 41 ds = new DatagramSocket(); 42 port = ds.getLocalPort(); 43 } catch (Exception e) { 44 throw new RuntimeException(e.getMessage()); 45 } 46 } 47 48 public void run() { 49 byte b[] = new byte[100]; 50 DatagramPacket dp = new DatagramPacket(b,b.length); 51 while (true) { 52 try { 53 ds.receive(dp); 54 String reply = new String(dp.getData(), dp.getOffset(), dp.getLength()); 55 ds.send(new DatagramPacket(reply.getBytes(),reply.length(), 56 dp.getAddress(),dp.getPort())); 57 if (reply.equals(msgs[msgs.length-1])) { 58 break; 59 } 60 } catch (Exception e) { 61 throw new RuntimeException(e.getMessage()); 62 } 63 } 64 ds.close(); 65 } 66 } 67 68 public static void main(String args[]) throws Exception { 69 ServerThread st = new ServerThread(); 70 st.start(); 71 DatagramSocket ds = new DatagramSocket(); 72 byte b[] = new byte[100]; 73 DatagramPacket dp = new DatagramPacket(b,b.length); 74 for (int i = 0; i < msgs.length; i++) { 75 ds.send(new DatagramPacket(msgs[i].getBytes(),msgs[i].length(), 76 InetAddress.getLocalHost(), 77 port)); 78 ds.receive(dp); 79 if (!msgs[i].equals(new String(dp.getData(), dp.getOffset(), dp.getLength()))) { 80 throw new RuntimeException("Msg expected: "+msgs[i] +msgs[i].length()+ 81 "msg received: "+new String(dp.getData(), dp.getOffset(), dp.getLength())+dp.getLength()); 82 } 83 } 84 ds.close(); 85 System.out.println("Test Passed!!!"); 86 } 87} 88