java.nio.*を使ったソケットクラサバ
戻る
::::::::::::::
NetClient.java
::::::::::::::
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
/**
$Id: NioSocket.html,v 1.1 2009/06/22 16:11:50 kishi Exp kishi $
*/
public class NetClient {
static public void main( String[] args ) throws Exception {
InetSocketAddress address = new InetSocketAddress( InetAddress.getByName( args[ 0 ] ), 80 );
SocketChannel channel = SocketChannel.open(); // オープン
channel.connect( address ); // サーバに接続
Charset charset = Charset.forName( "Shift_JIS" );
ByteBuffer message = charset.encode( "今日は!今日はいい天気ですね!" );
channel.write( message ); // 書き込み
ByteBuffer reply = ByteBuffer.allocate( 1024 );
channel.read( reply ); // 読み込み
reply.flip();
System.out.println( "Reply: " + charset.decode( reply ) );
channel.close();
}
}
::::::::::::::
NetServer.java
::::::::::::::
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
/**
$Id: NioSocket.html,v 1.1 2009/06/22 16:11:50 kishi Exp kishi $
@author KISHI Yasuhiro
*/
public class NetServer {
private Selector selector;
private Charset charset = Charset.forName( "Shift_JIS" );
public NetServer() {
try {
selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking( false ); // 非同期モードにする
InetSocketAddress address = new InetSocketAddress( InetAddress.getLocalHost(), 80 );
serverSocketChannel.socket().bind( address );
serverSocketChannel.register( selector, SelectionKey.OP_ACCEPT );
while ( selector.select() > 0 ) {
Set keys = selector.selectedKeys();
Iterator keyIterator = keys.iterator();
while ( keyIterator.hasNext() ) {
SelectionKey key = ( SelectionKey ) keyIterator.next();
keyIterator.remove(); // 選択されたキーを削除
if ( key.isAcceptable() ) {
ServerSocketChannel serverChannel = ( ServerSocketChannel ) key.channel();
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking( false ); // 非同期に変更
socketChannel.register( selector, SelectionKey.OP_READ );
System.out.println( socketChannel + " connect." );
} else if ( key.isReadable() ) {
SocketChannel channel = ( SocketChannel ) key.channel();
sendBack( channel );
}
}
}
serverSocketChannel.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
private void sendBack( SocketChannel socketChannel ) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate( 2048 );
socketChannel.read( buffer );
buffer.flip();
System.out.println( "確かに右記内容を受け取りました。" + charset.decode( buffer.duplicate() ) + " " + ( new Date() ).toString() );
socketChannel.write( buffer );
socketChannel.close();
}
public static void main( String[] args ) {
new NetServer();
}
}
戻る