[Advanced-java] What's The Difference Between...
Matthew.Salerno@Gunter.AF.mil
Matthew.Salerno at Gunter.AF.mil
Tue Mar 25 19:15:06 2003
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);
}
}
// ........