Rambler's Top100

А Б В Г Д Е Ж З И К Л М Н О П Р С Т У Ф Х Ц Ч Ш Э Ю Я

Все примеры | Примеры по пакетам

Простейший чат-сервер с использованием nio


package niochat1;
  //Простейший чат-сервер с использованием nio.  
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class nioChatServer implements Runnable
{
  
  private int port;

  private  ByteBuffer buffer1 = ByteBuffer.allocate( 1024 );
  private CharBuffer chBuffer1 = buffer1.asCharBuffer();
  Vector< SocketChannel> vsc=new  Vector< SocketChannel>();
  Vector< Socket> vs=new  Vector< Socket>();
  static Queue queue = new LinkedList();
  broadcast bc=null;
  
  public nioChatServer( int port ) {
    this.port = port;
    new Thread( this ).start();
  }
 Thread tr=new BasicThread();

  public void run() {
    try {
       
        tr.start();
      ServerSocketChannel ssc = ServerSocketChannel.open();

      ssc.configureBlocking( false );
      ServerSocket ss = ssc.socket();
      InetSocketAddress isa = new InetSocketAddress( port );
      ss.bind( isa );

        // Создать новый селектор  
      Selector selector = Selector.open();
        // Регистрация канала  
      ssc.register( selector, SelectionKey.OP_ACCEPT );
      System.out.println( "Слушается порт "+port );

      while (true) {

        int nmbs = selector.select();
        if (nmbs == 0) {
          continue;
        }

        Set keys = selector.selectedKeys();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
          SelectionKey key = (SelectionKey)it.next();

          if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
            SelectionKey.OP_ACCEPT) {

            System.out.println( "Принято" );
              // Регистрация сокета для входящего соединения  

            Socket s = ss.accept();
            System.out.println( "Соединен с "+s );

            vs.add(s);
            System.out.println( "vs "+vs );
            SocketChannel sc = s.getChannel();
            sc.configureBlocking( false );
              //Добавление SocketChannel в вектор  
            vsc.add(sc);
            sc.register( selector, SelectionKey.OP_READ );
          } else if ((key.readyOps() & SelectionKey.OP_READ) ==
            SelectionKey.OP_READ) {

            SocketChannel sc = null;

            try {

                // Обработка входных данных  
              sc = (SocketChannel)key.channel();
              boolean ok = processInput( sc );
                // Удаление мертвого соединения  
              if (!ok) {
                key.cancel();
                Socket s = null;
                try {
                  s = sc.socket();
                  s.close();
                } catch( IOException ie ) {
                }
              }

            } catch( IOException ie ) {

              key.cancel();
              try {
                sc.close();
              } catch( IOException ie2 ) { System.out.println( ie2 ); }

              System.out.println( "Закрыто "+sc );
            }
          }
        }

        keys.clear();
      }
    } catch( IOException ie ) {
      System.err.println( ie );
    }
  }

 class BasicThread extends Thread {
        public void run() {
            bc=new broadcast();
             bc.vsc=vsc;
        }
    }
  private boolean processInput( SocketChannel sc ) throws IOException {

    buffer1.flip();
    buffer1.clear();
    chBuffer1.clear();
   sc.read( buffer1 );

    if (buffer1.limit()==0) {
      return false;
    }

    String str = "";
    str=chBuffer1.toString();
    str=str.trim();

        buffer1.flip();
        buffer1.clear();
        chBuffer1.clear();
        chBuffer1.put("resp = "+str);
 
        bc.vsc=vsc;
        bc.sendMessage(str);
   System.out.println("str "+str);
    return true;
  }

  static public void main( String args[] ) throws Exception {
    int port = Integer.parseInt( "9999");
    new nioChatServer( port );
  }
}
16.05.2009


Чат-клиент. Реализована клиентская логика
Форма чат-клиента
Форма логина в чат
Rambler's Top100


Ассоциативные ссылки