向SocketChannel写入数据并读取返回数据

               
  1. package net.java2000.nio;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.SocketChannel;
  6. /**
  7.  * 向SocketChannel写入数据并读取返回数据。
  8.  * 
  9.  * @author 赵学庆,Java世纪网(java2000.net)
  10.  * 
  11.  */
  12. public class SocketChannelWrite {
  13.   public static SocketChannel createSocketChannel(String hostName, int port)
  14.       throws IOException {
  15.     SocketChannel sChannel = SocketChannel.open();
  16.     sChannel.configureBlocking(false);
  17.     sChannel.connect(new InetSocketAddress(hostName, port));
  18.     return sChannel;
  19.   }
  20.   public static void main(String[] args) {
  21.     ByteBuffer buf = ByteBuffer.allocateDirect(1024);
  22.     try {
  23.       buf.clear();
  24.       SocketChannel socketChannel = createSocketChannel("www.163.com"80);
  25.       while (!socketChannel.finishConnect()) {
  26.         System.out.println("等待非阻塞连接建立....");
  27.         try {
  28.           Thread.sleep(10);
  29.         } catch (InterruptedException e) {
  30.           e.printStackTrace();
  31.         }
  32.       }
  33.       buf.put("get / /n/n".getBytes());
  34.       buf.flip();
  35.       socketChannel.write(buf);
  36.       buf.clear();
  37.       int numBytesRead;
  38.       while ((numBytesRead = socketChannel.read(buf)) != -1) {
  39.         if (numBytesRead == 0) {
  40.           // 如果没有数据,则稍微等待一下
  41.           try {
  42.             Thread.sleep(1);
  43.           } catch (InterruptedException e) {
  44.             e.printStackTrace();
  45.           }
  46.           continue;
  47.         }
  48.         // 转到最开始
  49.         buf.flip();
  50.         while (buf.remaining() > 0) {
  51.           System.out.print((char) buf.get());
  52.         }
  53.         // 也可以转化为字符串,不过需要借助第三个变量了。
  54.         // buf.get(buff, 0, numBytesRead);
  55.         // System.out.println(new String(buff, 0, numBytesRead, "UTF-8"));
  56.         // 复位,清空
  57.         buf.clear();
  58.       }
  59.     } catch (IOException e) {
  60.       e.printStackTrace();
  61.     }
  62.   }
  63. }

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/jgfyyfd/article/details/86605013
今日推荐