JAVA Socket编程学习6--NIOTCP两个线程监听两个端口

本文代码来自:http://bbs.csdn.net/topics/390748964


客户端代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Set;
 
public class NIOClient implements Runnable{
    private ByteBuffer sBuffer = ByteBuffer.allocate(1024);  
    private ByteBuffer rBuffer = ByteBuffer.allocate(1024);  
    private InetSocketAddress SERVER;  
    private Selector selector;  
    private SocketChannel client;  
    private String receiveText;  
    private String sendText;  
    private int count=0;  
       
    public NIOClient(int port){  
        SERVER = new InetSocketAddress("localhost", port);  
        init(); 
    }
    public void init(){  
        try {  
            SocketChannel socketChannel = SocketChannel.open();  
            socketChannel.configureBlocking(false);  
            selector = Selector.open();  
            socketChannel.register(selector, SelectionKey.OP_CONNECT);  
            socketChannel.connect(SERVER);  
             
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
       
    private void handle(SelectionKey selectionKey) throws IOException{  
        if (selectionKey.isConnectable()) {  
            client = (SocketChannel) selectionKey.channel();  
            if (client.isConnectionPending()) {  
                client.finishConnect();  
                System.out.println("connect success !");  
                sBuffer.clear();  
                sBuffer.put((new Date().toLocaleString()+" connected!").getBytes());  
                sBuffer.flip();  
                client.write(sBuffer);
                new Thread(){  
                    @Override  
                    public void run() {  
                        while(true){  
                            try {  
                                sBuffer.clear();  
                                InputStreamReader input = new InputStreamReader(System.in);  
                                BufferedReader br = new BufferedReader(input);  
                                sendText = br.readLine();  
                                sBuffer.put(sendText.getBytes());  
                                sBuffer.flip();  
                                client.write(sBuffer);  
                            } catch (IOException e) {  
                                e.printStackTrace();  
                                break;  
                            }  
                      }  
                    };  
                }.start();  
            }  
            client.register(selector, SelectionKey.OP_READ);  
        } else if (selectionKey.isReadable()) {  
            client = (SocketChannel) selectionKey.channel();  
            rBuffer.clear();  
            count=client.read(rBuffer);  
            if(count>0){  
                receiveText = new String( rBuffer.array(),0,count);  
                System.out.println(receiveText);  
                client = (SocketChannel) selectionKey.channel();  
                client.register(selector, SelectionKey.OP_READ);  
            }  
        }   
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
        while (true) {  
            selector.select();
            Set<SelectionKey> keySet = selector.selectedKeys();  
            for(final SelectionKey key : keySet){  
                handle(key);
            };  
            keySet.clear();  
        }  
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
    
    public static void main(String args[]){
    	NIOClient client1 = new NIOClient(7788);  
        new Thread(client1).start();
    }
}
服务端代码:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class NIOSServer implements Runnable{
    private int port = 8888;
    private Charset cs = Charset.forName("gbk"); 
    private ByteBuffer sBuffer = ByteBuffer.allocate(1024);  
    private ByteBuffer rBuffer = ByteBuffer.allocate(1024);  
    private Map<String, SocketChannel> clientsMap = new HashMap<String, SocketChannel>();  
    private Selector selector;  
       
    public NIOSServer(int port){  
        this.port = port;  
        try {  
            init();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    private void init() throws IOException{  
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
        serverSocketChannel.configureBlocking(false);  
        ServerSocket serverSocket = serverSocketChannel.socket();  
        serverSocket.bind(new InetSocketAddress(port));  
        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
        System.out.println("server start on port:"+port);  
    }  
 
    private void listen(){   
    } 
     
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {  
            try {  
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();  
                for(SelectionKey key : selectionKeys){  
                    handle(key);  
                }  
                selectionKeys.clear();
            } catch (Exception e) {  
                e.printStackTrace();  
                break;  
            }  
               
        }  
    } 
    private void handle(SelectionKey selectionKey) throws IOException, InterruptedException {  
        ServerSocketChannel server = null;  
        SocketChannel client = null;  
        String receiveText=null;  
        int count=0;  
        if (selectionKey.isAcceptable()) {  
            server = (ServerSocketChannel) selectionKey.channel();  
            client = server.accept();
            //判断client 是否为空
            if(client != null){
                client.configureBlocking(false);  
                client.register(selector, SelectionKey.OP_READ);
            }
//            Thread.sleep(10*1000);
        } else if (selectionKey.isReadable()) {  
            client = (SocketChannel) selectionKey.channel();  
            rBuffer.clear();  
            count = client.read(rBuffer);  
            if (count > 0) {  
                rBuffer.flip();  
                receiveText = String.valueOf(cs.decode(rBuffer).array());  
                System.out.println(client.toString()+":"+receiveText);  
                dispatch(client, receiveText);  
                client = (SocketChannel) selectionKey.channel();  
                client.register(selector, SelectionKey.OP_READ);  
            }  
        }   
    }  
       
    private void dispatch(SocketChannel client,String info) throws IOException{  
        Socket s = client.socket();  
        String name = "["+s.getInetAddress().toString().substring(1)+":"+Integer.toHexString(client.hashCode())+"]";  
        if(!clientsMap.isEmpty()){  
            for(Map.Entry<String, SocketChannel> entry : clientsMap.entrySet()){  
                SocketChannel temp = entry.getValue();  
                if(!client.equals(temp)){  
                    sBuffer.clear();  
                    sBuffer.put((name+":"+info).getBytes());  
                    sBuffer.flip();    
                    temp.write(sBuffer);  
                }  
            }  
        }  
        clientsMap.put(name, client);  
    }  
     
    public static void main(String[] args) throws InterruptedException {
        //创建NIOSServer
        NIOSServer server1 = new NIOSServer(7778);  
        NIOSServer server2 = new NIOSServer(7777);  
        new Thread(server1).start();
        new Thread(server2).start();
//        Thread.sleep(10*1000);
        //创建NIOClient 
        NIOClient client1 = new NIOClient(7778);  
        new Thread(client1).start();
        NIOClient client2 = new NIOClient(7777);  
        new Thread(client2).start();
        NIOClient client3 = new NIOClient(7778);  
        new Thread(client3).start();
        NIOClient client4 = new NIOClient(7777);  
        new Thread(client4).start();
    }
}
运行NIOSServer,输出:
server start on port:7778
server start on port:7777
connect success !
connect success !
connect success !
connect success !
java.nio.channels.SocketChannel[connected local=/127.0.0.1:7778 remote=/127.0.0.1:51700]:2017-11-7 15:46:06 connected!
java.nio.channels.SocketChannel[connected local=/127.0.0.1:7777 remote=/127.0.0.1:51709]:2017-11-7 15:46:06 connected!
java.nio.channels.SocketChannel[connected local=/127.0.0.1:7778 remote=/127.0.0.1:51706]:2017-11-7 15:46:06 connected!
java.nio.channels.SocketChannel[connected local=/127.0.0.1:7777 remote=/127.0.0.1:51703]:2017-11-7 15:46:06 connected!
[127.0.0.1:228079cf]:2017-11-7 15:46:06 connected!
[127.0.0.1:7c721de]:2017-11-7 15:46:06 connected!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值