天天看点

NIO实现TCP数据传输

 TCP

import java.nio.*;

import java.nio.channels.*;

import java.net.*;

import java.io.IOException;

public class StateClient {

  public  int port = 8000;

  public  String host = "127.0.0.1";

  public StateClient() {

  }

  public static void main(String[] args) {

    StateClient client = new StateClient();

    client.process();

  }

  public void process(){

    try {

      SocketAddress address = new InetSocketAddress(host, port);

      SocketChannel client = SocketChannel.open(address);

      ByteBuffer buffer = ByteBuffer.allocate(74);

      String s = "sdf好 sfds";

      //准备发送

      buffer.clear();

      buffer.put(s.getBytes());

      buffer.flip();

      client.write(buffer);

      //接收到缓存中

      buffer.clear();

      try{

      client.read(buffer);

      }catch(IOException ex){

      System.out.println("没有数据");

      }

      buffer.flip();

      byte []b = new byte[buffer.limit()];

      for(int i = 0; i < buffer.remaining();i++)

      {

        b[i] = buffer.get(i);

      }

      String ss = new String(b,"gb2312");

      System.out.println(ss);

    }

    catch (IOException ex) {

      ex.printStackTrace();

    }

  }

}

/TCP-----server

//package test.frame;

import java.io.*;

import java.net.*;

import java.nio.*;

import java.lang.*;

import java.nio.channels.*;

import java.nio.charset.*;

import java.util.*;

public class StateServer

    implements Runnable

{

  private int port;

  private final ByteBuffer buffer = ByteBuffer.allocate( 1024 );

  public StateServer( int port ) {

    this.port = port;

    new Thread( this ).start();

  }

  public void run() {

    try {

      ServerSocketChannel ssc = ServerSocketChannel.open();

      ssc.configureBlocking( false );

      ServerSocket ss = ssc.socket();

      InetSocketAddress address = new InetSocketAddress( port );

      ss.bind( address );

      // Create a new Selector for selecting

      Selector selector = Selector.open();

      ssc.register( selector, SelectionKey.OP_ACCEPT );

      System.out.println( "Listening on port "+port );

      while (true) {

        int num = selector.select();

        if (num == 0) {

          continue;

        }

        Set keys = selector.selectedKeys();

        Iterator it = keys.iterator();

        while (it.hasNext()) {

          SelectionKey key = (SelectionKey)it.next();

          // What kind of activity is it?

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

            SelectionKey.OP_ACCEPT) {

//            System.out.println( "acc" );

            Socket s = ss.accept();

//            System.out.println( "Got connection from "+s );

            SocketChannel sc = s.getChannel();

            sc.configureBlocking( false );

            // Register it with the selector, for reading

            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 the connection is dead, then remove it

              // from the selector and close it

              if (!ok) {

                key.cancel();

                Socket s = null;

                try {

                  s = sc.socket();

                  s.close();

                } catch( IOException ie ) {

                  System.err.println( "Error closing socket "+s+": "+ie );

                }

              }

            } catch( IOException ie ) {

              // On exception, remove this channel from the selector

              key.cancel();

              try {

                sc.close();

              } catch( IOException ie2 ) { System.out.println( ie2 ); }

              System.out.println( "Closed "+sc );

            }

          }

        }

        keys.clear();

      }

    } catch( IOException ie ) {

      System.err.println( ie );

    }

  }

// 从接收端口通道中把数据读如缓存,然后进行事务处理,把结果通过缓存用通道传回去

  private boolean processInput( SocketChannel sc ) throws IOException {

         int bytesEchoed = 0;

         String s = "";

               while (true) {

                 buffer.clear();

//                 System.out.println("rr::::");

                 int r = sc.read( buffer );

//                 System.out.println("rr::::"+r);

                 //读完数据就跳出循环

                 if (r == 0) {

                   break;

                 }

                 buffer.flip();

                 //打印输入

//                 System.out.println("ceshi11:::");

                 byte b[] =new byte[buffer.remaining()];

                 for (int i=0; i<buffer.remaining(); ++i) {

                    b[i]= buffer.get(i);

                   //System.out.println("bb:::"+b[i]);

                 }

                  s =new String(b, "GB2312");

//                 System.out.println("1111111:::::::::"+s);

                 //接受后返回信息

                 sc.write(buffer );

                 //bytesEchoed += r;

               }

        return true;

      }

  static public void main( String args[] ) throw* **ception {

    int port = 8000;//Integer.parseInt( args[0] );

    new StateServer( port );

  }

 }