Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing sockets in java

Tags:

java

sockets

I have a class which is a socket client and I am trying to unit test its methods. The tests require that I start a socket server before each test so I use:

@Before
public void setUp() {
    if (myServerSocket == null) {
    Thread myThread = new Thread() {
        public void run() {
            DataInputStream dis = null;
            DataOutputStream dos = null;
            try {
                ServerSocket myServer = new ServerSocket(port);
                myServerSocket = myServer.accept();
                dis = new DataInputStream(myServerSocket.getInputStream());
                dos = new DataOutputStream(myServerSocket.getOutputStream());
                byte[] bytes = new byte[10];
                dis.read(bytes);
                boolean breakLoop = false;
                do {
                    if (new String(bytes).length() != 0) {
                        dos.writeBytes(serverMessage + "\n");
                        dos.flush();
                        breakLoop = true;
                        dos.writeBytes("</BroadsoftDocument>" + "\n");
                        dos.flush();
                    }
                } while (!breakLoop);
            } 
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    myThread.start();
    }
} 

After each test I try to close the server socket so I can reopen the server socket for the next test:

@After
public void tearDown() throws IOException, BroadsoftSocketException {
    System.out.println("@After");
    if (myServerSocket != null) {
        myServerSocket.close();
        myServerSocket = null;
            try {
                Thread.sleep(5000);
            } 
            catch (InterruptedException e) {
                // do nothing.
            }
    }
}

However, I get "java.net.BindException: Address already in use: JVM_Bind" before each test starting with the second test. I realize I am trying to use the same port for each test but shouldn't closing the socket free up the port?

like image 504
badgerduke Avatar asked Nov 16 '25 21:11

badgerduke


1 Answers

Quite possibly your socket is still in TIME_WAIT state when you attempt to reconnect it. I would recommend mocking such external dependencies, but if you really do find yourself wanting to continue using a real socket then try setting rebind options. In your setup function, instead of ServerSocket myServer = new ServerSocket(port); do :

final ServerSocket myServer = new ServerSocket();
myServer.setReuseAddress(true);
myServer.bind(new java.net.InetSocketAddress(port));
like image 133
Perception Avatar answered Nov 19 '25 11:11

Perception



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!