summaryrefslogtreecommitdiffstats
path: root/simple/simple-transport/src/test/java/org/simpleframework/transport/ServerBuffer.java
blob: 34cdc0c23428800f039e994d85b13e7480e0501a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package org.simpleframework.transport;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.util.concurrent.CountDownLatch;

public class ServerBuffer extends Thread {

   private ByteArrayOutputStream buffer;
   private ServerSocket server;
   private CountDownLatch latch;

   public ServerBuffer() throws Exception {
      this.buffer = new ByteArrayOutputStream();
      this.latch = new CountDownLatch(1);
      this.server = getSocket();     
      this.start();
   }
   
   public ByteArrayOutputStream getBuffer(){
      return buffer;
   }
   
   public void awaitClose() throws Exception {
      latch.await();
   }
   
   public int getPort() {
      return server.getLocalPort();
   }
   
   private ServerSocket getSocket() throws Exception {
      // Scan the ephemeral port range
      for(int i = 2000; i < 10000; i++) { // keep trying to grab the socket 
         try {
            ServerSocket socket = new ServerSocket(i);
            System.out.println("port=["+socket.getLocalPort()+"]");
            return socket;
         } catch(Exception e) {
            Thread.sleep(200);
         }
      }
      // Scan a second time for good measure, maybe something got freed up
      for(int i = 2000; i < 10000; i++) { // keep trying to grab the socket 
         try {
            ServerSocket socket = new ServerSocket(i);
            System.out.println("port=["+socket.getLocalPort()+"]");
            return socket;
         } catch(Exception e) {
            Thread.sleep(200);
         }
      }
      throw new IOException("Could not create a client socket");
   }

   public void run() {
      try {
         java.net.Socket socket = server.accept();
         InputStream in = socket.getInputStream();
         int count = 0;
         
         while((count = in.read()) != -1) {
            buffer.write(count);
            System.err.write(count);
            System.err.flush();
         }
      } catch(Exception e) {
         e.printStackTrace();
      } finally {
         latch.countDown();
      }
   }
}