socketクライアントのノンブロッキング対応

戻る

import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;

/**
$Id: Client.java,v 1.21 2007/03/04 07:36:30 kishi Exp kishi $
*/

public class Client {

    static public void main ( String[] args ) throws Exception {

        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking ( false );

        InetSocketAddress addr = new InetSocketAddress ( InetAddress.getByName ( args[0] ), 80 );
        channel.connect ( addr );

        Selector selector = Selector.open();

        channel.register ( selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE );

        Charset charset = Charset.forName ( "Shift_JIS" );
        while ( selector.select ( 500 ) > 0 ) {

            Iterator i = selector.selectedKeys().iterator();

            while ( i.hasNext() ) {
                SelectionKey key = ( SelectionKey ) i.next();

                i.remove();

                channel = ( SocketChannel ) key.channel();

                if ( key.isConnectable() ) {
                    if ( channel.isConnectionPending() ) {
                        channel.finishConnect();
                        System.err.println ( "Connection established!!!" );
                    }
                }
                if ( key.isWritable() ) {
                    System.err.println ( "WRITEABLE" );

                    ByteBuffer message = charset.encode ( "GET / HTTP/1.0\n\n" );
                    channel.write ( message ); // 書き込み
                }
                if ( key.isReadable() ) {
                    System.err.println ( "READABLE" );

                    ByteBuffer reply = ByteBuffer.allocate ( 1024 );
                    channel.read ( reply ); // 読み込み
                    reply.flip();
                    System.out.println ( "Reply: " + charset.decode ( reply ) );

                    channel.close();
                }
            }
        }

    }

}


戻る

inserted by FC2 system