1. 程式人生 > >NIO實現TCP資料傳輸

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 );
  }
 }