[Advanced-java] What's The Difference Between...

Nicholas Wright nick at ist.co.uk
Wed Mar 26 10:06:20 2003


Hi Matthew,

The main difference between SocketChannels and Sockets is that 
SocketChannels use non-blocking communication.  You generally have a number 
of "SocketChannels" and you poll each one to see if there is data to read 
or not.  You do this with a Selector.

You register each SocketChannel with a Selector.  At your leisure, you can 
either wait for data to be available on any of the SocketChannels, or you 
can "poll" it every now and then with the use of the "select()" and 
"select(long timeout)" methods.

You have full control of the IO on that socket, and have no worries of 
blocking threads, or nastier blocking close() operations.


Some people might say, "Ahha... but you can do non-blocking IO with normal 
Socket!", but this is blatently not true.  They'd give source code like 
this:

	Socket s = serverSocket.accept();
	InputStream is = s.getInputStream();
	// Data available to read?
	long bytes = is.available();
	
If there's nothing to read, I believe available() will actually block.


The NBTimeServer example below is probably the best source code to 
demonstrate non-blocking I/O:
http://java.sun.com/j2se/1.4/docs/guide/nio/example/NBTimeServer.java

This example is more cluttered but also uses the non-blocking API.
http://java.sun.com/j2se/1.4/docs/guide/nio/example/Ping.java

Best Regards

Nicholas


> GIVEN:
> I have a GUI java app running on a client machine that will connect to a
> server.  I am creating java classes to run as a process on a Server that
> will be listening for and accepting connections from users.  Once a user=
 
is
> connected, the server will transmit data to/from the client until the 
client
> chooses to disconnect. 
> 
> QUESTION:
> Based on this vague example, Can anyone tell me the benefits of using a
> SocketChannel (EX 1 below) over using a regular Socket (EX 2 below)?  I=
 
have
> been told if you are expecting NUMEROUS clients to connect and transmit
> data, then EX 1 is better... Any of you guys support that assumption?
> 
> 
> /* EX 1 */
> 	// ........
> 			ServerSocketChannel serverSocketChannel =
> ServerSocketChannel.open();
> 			ServerSocket serverSocket =
> serverSocketChannel.socket();
> 
> 			serverSocket.bind(new InetSocketAddress(9000));
> 
> 			while(true)
> 			{
> 				System.out.println("Awaiting Client
> Connection...");
> 				SocketChannel socketChannel =
> serverSocketChannel.accept();
> 				System.out.println("Got Client
> Connection...");
> 				// Create a byte buffer...
> 				String stringToSend = "This is a message";
> 
> 				int length = stringToSend.length() * 2; // 
*
> 2 due to size of each char
> 
> 				ByteBuffer lengthInBytes =
> ByteBuffer.allocate(4);	// 4 = size of an 'int'
> 				lengthInBytes.putInt(length);
> 				lengthInBytes.rewind();
> 				
> 				ByteBuffer dataToSend =
> ByteBuffer.allocate(length);
> 				
dataToSend.asCharBuffer().put(stringToSend);
> 				ByteBuffer sendArray[] = {lengthInBytes,
> dataToSend};
> 
> 				socketChannel.write(sendArray);
> 				System.out.println("Sent Message to
> Client...");
> 			}
> 	// ........
> 
> /* END OF EX 1 */
> 
> 
> /* EX 2 */
> 	// ........
> 		// create the server socket...
> 		try
> 		{
> 			serverSocket = new ServerSocket(port);
> 		}
> 		catch(IOException e)
> 		{
> 			System.out.println("-> Could not create Server on
> port "+port);
> 			System.exit(1);
> 		}
> 		
> 		System.out.println("-> Server created on port "+port);
> 		}
> 		
> 		// ........	
> 
> 		while(true)
> 		{
> 			// wait for a client connection...
> 			try
> 			{
> 				System.out.println("-> Waiting for client
> connections...");
> 				new ClientHandler(serverSocket.accept());
> 
> 			}
> 			catch(IOException e)
> 			{
> 				System.out.println("-> Error accepting
> client connection: "+e);
> 			}
> 		}
> 	// ........
> 	
> _______________________________________________
> Advanced-java mailing list
> Advanced-java@lists.xcf.berkeley.edu
> http://lists.xcf.berkeley.edu/mailman/listinfo/advanced-java

===========================================================================
Nicholas Wright    Imperial Software Technology    Senior Software Engineer 
---------------------------------------------------------------------------
Email : nick.wright@ist.co.uk or support@ist.co.uk
Kings Court                            120 Hawthorne Ave, #101
185 Kings Road                         Palo Alto
Reading RG1 4EX United Kingdom         California 94301 USA
Tel: +44 118 958 7055                  Tel: 650 688 0200
FAX: +44 118 958 9005                  FAX: 650 688 1054
===========================================================================  
******              VISAJ AT http://www.ist.co.uk/visaj              ******
===========================================================================