中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java NIO怎么實現聊天室程序

發布時間:2022-01-14 20:15:05 來源:億速云 閱讀:152 作者:iii 欄目:編程語言

本文小編為大家詳細介紹“Java NIO怎么實現聊天室程序”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Java NIO怎么實現聊天室程序”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

服務端:

package test.javanio;   /**   * @author    * @version    * CreateTime:2010-12-1 下午05:12:11   * Description:   */ import java.io.IOException;  import java.net.InetSocketAddress;  import java.nio.ByteBuffer;  import java.nio.channels.SelectionKey;  import java.nio.channels.Selector;  import java.nio.channels.ServerSocketChannel;  import java.nio.channels.SocketChannel;  import java.util.Date;  import java.util.Iterator;  import java.util.logging.Level;  import java.util.logging.Logger;   public class MySocketServer implements Runnable {       private boolean running;       private Selector selector;      String writeMsg;      StringBuffer sb = new StringBuffer();      SelectionKey ssckey;       public MySocketServer() {           running = true;       }       public void init() {          try {              selector = Selector.open();              ServerSocketChannel ssc = ServerSocketChannel.open();              ssc.configureBlocking(false);              ssc.socket().bind(new InetSocketAddress(2345));              ssckey = ssc.register(selector, SelectionKey.OP_ACCEPT);              System.out.println("server is starting..." + new Date());          } catch (IOException ex) {              Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,                      null, ex);          }      }       public static void main(String[] args) {          MySocketServer server = new MySocketServer();          new Thread(server).start();       }       public void execute() {          try {              while (running) {                  int num = selector.select();                  if (num > 0) {                      Iterator<SelectionKey> it = selector.selectedKeys()                              .iterator();                      while (it.hasNext()) {                          SelectionKey key = it.next();                          it.remove();                          if (!key.isValid())                              continue;                          if (key.isAcceptable()) {                              System.out.println("isAcceptable");                              getConn(key);                          } else if (key.isReadable()) {                              System.out.println("isReadable");                              readMsg(key);                          }                           else if (key.isValid() && key.isWritable()) {                              if (writeMsg != null) {                                  System.out.println("isWritable");                                  writeMsg(key);                              }                           }                           else                             break;                       }                   }                  Thread.yield();              }           } catch (IOException ex) {              Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,                      null, ex);          }      }       private void getConn(SelectionKey key) throws IOException {          ServerSocketChannel ssc = (ServerSocketChannel) key.channel();          SocketChannel sc = ssc.accept();          sc.configureBlocking(false);          sc.register(selector, SelectionKey.OP_READ);          System.out.println("build connection :"                 + sc.socket().getRemoteSocketAddress());      }       private void readMsg(SelectionKey key) throws IOException {          sb.delete(0, sb.length());          SocketChannel sc = (SocketChannel) key.channel();          System.out.print(sc.socket().getRemoteSocketAddress() + " ");          ByteBuffer buffer = ByteBuffer.allocate(1024);          buffer.clear();          int len = 0;          StringBuffer sb = new StringBuffer();          while ((len = sc.read(buffer)) > 0) {              buffer.flip();              sb.append(new String(buffer.array(), 0, len));          }          if (sb.length() > 0)              System.out.println("get from client:" + sb.toString());          if (sb.toString().trim().toLowerCase().equals("quit")) {              sc.write(ByteBuffer.wrap("BYE".getBytes()));              System.out.println("client is closed "                     + sc.socket().getRemoteSocketAddress());              key.cancel();              sc.close();              sc.socket().close();           } else {              String toMsg = sc.socket().getRemoteSocketAddress() + "said:"                     + sb.toString();              System.out.println(toMsg);               writeMsg = toMsg;               /*               * Iterator<SelectionKey> it=key.selector().keys().iterator();               *                * while(it.hasNext()){ SelectionKey skey=it.next();               * if(skey!=key&&skey!=ssckey){ SocketChannel client=(SocketChannel)               * skey.channel(); client.write(ByteBuffer.wrap(toMsg.getBytes()));               * }               *                * }               */              /*               *                * key.attach(toMsg);               * key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);               */             Iterator<SelectionKey> it = key.selector().keys().iterator();               while (it.hasNext()) {                  SelectionKey skey = it.next();                  if (skey != key && skey != ssckey) {                      if (skey.attachment() != null) {                          String str = (String) skey.attachment();                          skey.attach(str + toMsg);                      } else {                          skey.attach(toMsg);                      }                      skey                              .interestOps(skey.interestOps()                                      | SelectionKey.OP_WRITE);                  }               }              selector.wakeup();// 可有可無           }       }       public void run() {          init();          execute();      }       private void writeMsg(SelectionKey key) throws IOException {           System.out.println("++++enter write+++");          SocketChannel sc = (SocketChannel) key.channel();          String str = (String) key.attachment();           sc.write(ByteBuffer.wrap(str.getBytes()));          key.interestOps(SelectionKey.OP_READ);      }  }

客戶端:

package test.javanio;   /**   * @author    * @version    * CreateTime:2010-12-1 下午05:12:46   * Description:   */ import java.io.BufferedReader;  import java.io.IOException;  import java.io.InputStreamReader;  import java.net.InetSocketAddress;  import java.nio.ByteBuffer;  import java.nio.channels.Selector;  import java.nio.channels.SocketChannel;  import java.util.logging.Level;  import java.util.logging.Logger;  import java.util.Currency.*;   public class MySocketClient implements Runnable {      Selector selector;       boolean running;       SocketChannel sc;       public MySocketClient() {          running = true;       }       public void init() {          try {              sc = SocketChannel.open();              sc.configureBlocking(false);              sc.connect(new InetSocketAddress("localhost", 2345));           } catch (IOException ex) {              Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,                      null, ex);          }      }       public static void main(String[] args) {           MySocketClient client = new MySocketClient();          new Thread(client).start();      }       public void execute() {           int num = 0;          try {              while (!sc.finishConnect()) {              }          } catch (IOException ex) {              Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,                      null, ex);          }           ReadKeyBoard rkb = new ReadKeyBoard();          new Thread(rkb).start();          while (running) {              try {                   ByteBuffer buffer = ByteBuffer.allocate(1024);                  buffer.clear();                   StringBuffer sb = new StringBuffer();                  Thread.sleep(500);                   while ((num = sc.read(buffer)) > 0) {                      sb.append(new String(buffer.array(), 0, num));                      buffer.clear();                  }                  if (sb.length() > 0)                      System.out.println(sb.toString());                  if (sb.toString().toLowerCase().trim().equals("bye")) {                      System.out.println("closed....");                       sc.close();                      sc.socket().close();                      rkb.close();                      running = false;                  }              } catch (InterruptedException ex) {                  Logger.getLogger(MySocketClient.class.getName()).log(                          Level.SEVERE, null, ex);              } catch (IOException ex) {                  Logger.getLogger(MySocketClient.class.getName()).log(                          Level.SEVERE, null, ex);              }          }       }       public void run() {          init();          execute();      }       class ReadKeyBoard implements Runnable {           boolean running2 = true;           public ReadKeyBoard() {           }           public void close() {              running2 = false;          }           public void run() {              BufferedReader reader = new BufferedReader(new InputStreamReader(                      System.in));              while (running2) {                  try {                      System.out.println("enter some commands:");                      String str = reader.readLine();                      sc.write(ByteBuffer.wrap(str.getBytes()));                   } catch (IOException ex) {                      Logger.getLogger(ReadKeyBoard.class.getName()).log(                              Level.SEVERE, null, ex);                  }              }           }       }  }

讀到這里,這篇“Java NIO怎么實現聊天室程序”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

杨浦区| 东至县| 溧水县| 滁州市| 黄山市| 长岭县| 峡江县| 白山市| 德化县| 财经| 曲靖市| 永昌县| 新龙县| 莲花县| 克山县| 宜州市| 新河县| 五华县| 云林县| 普陀区| 望城县| 千阳县| 宁城县| 铜鼓县| 扶沟县| 绵阳市| 广东省| 洱源县| 都兰县| 富平县| 丹寨县| 来凤县| 九江市| 平和县| 左权县| 和政县| 察隅县| 西华县| 永济市| 筠连县| 浮梁县|