FileDocCategorySizeDatePackage
TestNonblockingSocket.javaAPI DocphoneME MR2 API (J2ME)3620Wed May 02 18:00:16 BST 2007com.sun.midp.io.j2me.socket

TestNonblockingSocket

public class TestNonblockingSocket extends TestCase

Fields Summary
static final int
PORT
static final String
TEST_MSG
ServerSocketConnection
server
SocketConnection
client
Constructors Summary
Methods Summary
public voidrunTests()

	setUp();

        declare("Test Nonblocking");
	testNonblocking();

	tearDown();
    
voidsetUp()


      
	try {
            // Create the server listening socket 
            server = (ServerSocketConnection) Connector.open("socket://:"+PORT);
	    // System.out.println("Server socket opened");
	    
	    // Create client socket
	    client = (SocketConnection)
		      Connector.open("socket://localhost:"+PORT);
	    // System.out.println("Client socket opened");
	} catch (IOException ioe) {
	    System.out.println("TestSocket setUp failed with:");
	    ioe.printStackTrace();
	}
    
voidtearDown()

	try {
	    // System.out.println("Closing connection");
            client.close();
            server.close();
	} catch (IOException e) {
	    System.out.println("TestSocket tearDown failed with:");
	    e.printStackTrace();
	}
    
voidtestNonblocking()
This test writes to client socket before accepting server socket. If client socket write is blocking, the server socket won't be responding to its write. Therefore, the accepting will fail. Passing this test proves that client socket write is nonblocking.

	try {
	    // Write to client socket
	    // System.out.println("Writing: " + TEST_MSG);
	    OutputStream os = client.openOutputStream();
	    os.write(TEST_MSG.getBytes());
	    os.close();

            // Wait for incoming connection to server socket
	    // System.out.println("Accepting serversocket");
            SocketConnection sc = (SocketConnection) server.acceptAndOpen();
	    // System.out.println("Accepted serversocket");

	    // Read from server socket
	    InputStream is = sc.openInputStream();
	    byte buf[] = new byte[2*TEST_MSG.length()];
	    int i = 0;
	    do {
                buf[i++] = (byte) is.read();
	    } while (buf[i-1] != -1 && buf[i-1] != '\n" && i < buf.length);

	    is.close();
	    sc.close();

	    String recvd = new String(buf, 0, i);
	    // System.out.println("recvd=\""+recvd+"\"");

            assertTrue(recvd.equals(TEST_MSG));

	} catch (IOException ioe) {
	    System.out.println("TestSocket:Nonblocking test failed with:");
	    ioe.printStackTrace();
	}