熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java NIO(異步IO)Socket通信例子

2022-06-13   來源: Java核心技術 

  //Java NIO (異步IO)Socket通信例子:

  服務器代碼:

  import *;

  import javanio*;

  import javaniochannels*;

  import javautil*;

  public class server

  {

  ServerSocketChannel ssc ;

  public void start()

  {

  try

  {

  Selector selector = Selectoropen();

  ServerSocketChannel ssc=ServerSocketChannelopen();

  nfigureBlocking(false);

  ServerSocket ss=sscsocket();

  InetSocketAddress address = new InetSocketAddress();

  ssbind(address);

  sscregister(selector SelectionKeyOP_ACCEPT);

  Systemoutprintln(端口注冊完畢!);

  while(true)

  {

  selectorselect();

  Set<SelectionKey> selectionKeys=selectorselectedKeys();

  Iterator<SelectionKey> iter=erator();

  ByteBuffer echoBuffer=ByteBufferallocate();

  SocketChannel sc;

  while(iterhasNext())

  {

  SelectionKey key=iternext();

  if((keyreadyOps()&SelectionKeyOP_ACCEPT)==SelectionKeyOP_ACCEPT)

  {

  ServerSocketChannel subssc=(ServerSocketChannel)keychannel();

  sc=subsscaccept();

  nfigureBlocking(false);

  scregister(selector SelectionKeyOP_READ);

  iterremove();

  Systemoutprintln(有新連接:+sc);

  }

  else if((keyreadyOps()&SelectionKeyOP_READ)==SelectionKeyOP_READ)

  {

  sc=(SocketChannel) keychannel();

  while(true)

  {

  echoBufferclear();

  int a;

  try

  {

  a=scread(echoBuffer);

  }

  catch(Exception e)

  {

  eprintStackTrace();

  break;

  }

  if(a==) break;

  if(a>)

  {

  byte[] b=echoBufferarray();

  Systemoutprintln(接收數據: +new String(b));

  echoBufferflip();

  scwrite(echoBuffer);

  Systemoutprintln(返回數據: +new String(b));

  }

  }

  scclose();

  Systemoutprintln(連接結束);

  Systemoutprintln(=============================);

  iterremove();

  }

  }

  }

  }

  catch (Exception e)

  {

  eprintStackTrace();

  }

  }

  }

  客戶端代碼:

  import *;

  import javanio*;

  import javaniochannels*;

  public class client

  {

  public void start()

  {

  try

  {

  SocketAddress address = new InetSocketAddress(localhost);

  SocketChannel client=SocketChannelopen(address);

  nfigureBlocking(false);

  String a=asdasdasdasddffasfas;

  ByteBuffer buffer=ByteBufferallocate();

  bufferput(agetBytes());

  bufferclear();

  int d=clientwrite(buffer);

  Systemoutprintln(發送數據: +new String(bufferarray()));

  while(true)

  {

  bufferflip();

  int i=clientread(buffer);

  if(i>)

  {

  byte[] b=bufferarray();

  Systemoutprintln(接收數據: +new String(b));

  clientclose();

  Systemoutprintln(連接關閉!);

  break;

  }

  }

  }

  catch(Exception e)

  {

  eprintStackTrace();

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25874.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.