0

UDPclient と UDPserver を Java nio で作成することにしました。しかし、私はいくつかのことを理解していません。ここにコードがあります

try {
  DatagramChannel channel = DatagramChannel.open();
  channel.configureBlocking(false);
  channel.connect(remote);
  //monitoring
  Selector selector = Selector.open();
  //read write keys
  channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);     
  ByteBuffer buffer = ByteBuffer.allocate(1024*64);//number of bytes for channel
  while (true) {
    selector.select(60000);//number of channels I think
    Set readyKeys = selector.selectedKeys();
    if (readyKeys.isEmpty()) { 
      break;
    }
    else {
      Iterator iterator = readyKeys.iterator();
      while (iterator.hasNext()) {
        SelectionKey key = (SelectionKey) iterator.next();
        iterator.remove();
        if (key.isReadable( )) {
          //read from buffer
          channel.read(buffer);
        } 
        if (key.isWritable()) {
          //write to buffer
          channel.write(buffer); 
        } 
      } 
    } 
  } 
} 
catch (IOException ex) {
  System.err.println(ex);
}  

コンソールに何かを書き込むと、イベントkey.isWritableは発生しますか? サーバーが何かイベントを送信すると、isReadable が発生しますか? また、たとえばユーザーが「GETL」または「REGR」(独自のメソッド) を書き込む場合に、イベントを操作する方法がわかりません。

4

2 に答える 2

1
  1. 渡す値selectは、チャネル数ではなくタイムアウトです。

  2. あなたがする必要があります

    DatagramChannel channelFromKey = (DatagramChannel) key.channel();

使用しないchannel

自分のイベントの意味がわかりません。そのキーが選択されたときにチャネルからデータグラムを読み取ります。

Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
    SelectionKey key = (SelectionKey) iterator.next();
    iterator.remove();
    if (key.isReadable( )) {
        DatagramChannel channelFromKey = 
             (DatagramChannel) key.channel();
        buffer.clear();
        // This is a DatagramChannel receive a datagram as a whole
        channelFromKey.receive(buffer);
    }
于 2012-04-05T22:40:14.793 に答える
0

コンソールに何かを書き込むと、key.isWritable のイベントが発生しますか?

いいえ。発生するイベントは、セレクターに登録したチャンネルのみです。コンソールに関係するチャネルを登録しておらず、ネットワークチャネルのみが SelectableChannels であるため登録できません。そのため、コンソールから発信されたイベントがセレクタを介して表示されることを期待する必要があります。

サーバーが何かイベントを送信すると、isReadable が発生しますか?

はい。

また、たとえばユーザーが「GETL」または「REGR」(独自のメソッド) を書き込む場合に、イベントを操作する方法がわかりません。

私もそうではありません。質問の意味さえ理解できません。セレクターから取得する唯一のイベントは、セレクターに登録したチャンネルで定義されたものです。

于 2012-04-06T00:41:28.333 に答える