📄 quoteclient.java
字号:
package com.wrox.quote;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class QuoteClient
{
// Define my favorite default port. Just look at a phone ;)
private static final int DEFAULT_PORT = 7236;
// The buffer to hold the incoming data
private static ByteBuffer buffer = ByteBuffer.allocateDirect( 1024 );
/**
* Asks for a quote
*/
private static void requestQuote( String host,
int port ) throws IOException
{
InetSocketAddress socketAddress = new InetSocketAddress(
InetAddress.getByName( host ),
port );
SocketChannel socketChannel = null;
try
{
// Connect to the Quote Server
socketChannel = SocketChannel.open();
socketChannel.connect( socketAddress );
// As recommended by the API docs, clear the buffer before
// a channel read or put operation to fill the buffer.
buffer.clear();
socketChannel.read( buffer );
// After a read or put operation, the flip() call resets the
// limit, position and any marks such that the buffer's data
// is ready for use. See the API docs for more details.
buffer.flip();
Charset charset = Charset.forName( "US-ASCII" );
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode( buffer );
System.out.print( charBuffer );
}
finally
{
if( socketChannel != null )
{
socketChannel.close();
}
}
}
public static void main(String[] args)
{
if( args.length == 0 )
{
System.err.println( "Syntax: java QuoteClient " +
"[QuoteServer host] [port number " +
"to request a connection on.]" );
System.exit( 1 );
}
// Get the host from the commandline.
String host = args[0];
int port = DEFAULT_PORT;
// Check to see if a port number was supplied.
if( args.length == 2 )
{
try
{
port = Integer.parseInt( args[1] );
}
catch( NumberFormatException nfe )
{
System.err.println( "Syntax: java QuoteClient " +
"[QuoteServer host] [port number " +
"to request a connection on.]" );
System.exit( 1 );
}
}
// Make a request.
try
{
QuoteClient.requestQuote( host, port );
}
catch( Exception e )
{
System.err.println( "Error: " + e );
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -