- package night;
 - import java.net .InetSocketAddress;
 - import java.io .IOException;
 - import java.io .BufferedReader;
 - import java.io .InputStreamReader;
 - import java.nio.ByteBuffer;
 - import java.nio.channels .SocketChannel;
 - import java.nio.channels.*;
 - public class Kfd extends Thread {
 - /**
 - * @param args
 - */
 - public static void main(String[] args) {
 - // TODO Auto-generated method stub
 - new Kfd();
 - System.out.println("请输入:");
 - }
 - static SocketChannel sc;
 - String host="127.0.0.1";
 - int port=10000;
 - ByteBuffer readbuf =ByteBuffer.allocate(1024);
 - ByteBuffer writebuf=ByteBuffer.allocate(1024);
 - InetSocketAddress ad=new InetSocketAddress(host,port);
 - public Kfd (){
 - start();
 - try {sc=SocketChannel.open();
 - Selector sl=Selector.open();
 - sc.configureBlocking(false);
 - //连接到server;
 - sc.connect(ad);
 - System.out.println("客服端连接成功");
 - if(!sc.finishConnect()){
 - System.out.print("客户端连接失败");
 - }
 - } catch (Exception e) {
 - // TODO: handle exception
 - e.printStackTrace();
 - }
 - }
 - public void run() {
 - while(true){
 - try {
 - BufferedReader buf=
 - new BufferedReader
 - (new InputStreamReader(System.in));
 - String str =buf.readLine();
 - byte[]pack=str.getBytes();
 - writebuf.clear();
 - writebuf.put(pack);
 - writebuf.flip();
 - System.out.println("到这里");
 - //发送
 - send(sc);
 - //接受
 - recive(sc);
 - }
 - catch (Exception e) {
 - // TODO: handle exception
 - e.printStackTrace();
 - }
 - }
 - }
 - private void recive(SocketChannel sc)throws IOException{
 - while(true){
 - if(sc.isConnectionPending()){
 - sc.read(readbuf);
 - }
 - readbuf.flip();
 - byte[]pack=null;
 - pack=new byte[readbuf.limit()];
 - //将缓冲的数据打包到数组中
 - readbuf.get(pack);
 - System.out.println(new String(pack.toString()));
 - }
 - }
 - private void send(SocketChannel sc){
 - while(true){
 - while(writebuf.hasRemaining()){
 - try {
 - sc.write(writebuf);
 - } catch (Exception e) {
 - // TODO: handle exception
 - e.printStackTrace();
 - }
 - }
 - }
 - }
 - }
 
原文链接:http://refly.iteye.com/blog/1053152

创新互联主要业务有网站营销策划、网站设计、网站制作、微信公众号开发、小程序制作、H5高端网站建设、程序开发等业务。一次合作终身朋友,是我们奉行的宗旨;我们不仅仅把客户当客户,还把客户视为我们的合作伙伴,在开展业务的过程中,公司还积累了丰富的行业经验、成都全网营销推广资源和合作伙伴关系资源,并逐渐建立起规范的客户服务和保障体系。
                文章标题:多线程NIO客户端实例
                
                网页地址:http://www.csdahua.cn/qtweb/news9/32909.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网