1. 程式人生 > 其它 >003-核心技術-IO模型-NIO-基於NIO群聊示例

003-核心技術-IO模型-NIO-基於NIO群聊示例

003-核心技術-IO模型-NIO-基於NIO群聊示例

一、基於上節編寫基礎聊天

GroupChatServer

package com.github.bjlhx15.netty.demo.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    private Selector selector;
    private
ServerSocketChannel listenerChannel; private static final int PORT = 6667; public GroupChatServer() { try { selector = Selector.open(); listenerChannel = ServerSocketChannel.open(); listenerChannel.bind(new InetSocketAddress(PORT)); listenerChannel.configureBlocking(
false); listenerChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { e.printStackTrace(); } } public void listen() { try { while (true) { int count = selector.select(2000); if (count > 0) { Iterator
<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { SocketChannel socketChannel = listenerChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); System.out.println(socketChannel.getRemoteAddress() + " 上線"); } if (key.isReadable()) { readData(key); } //刪除key防止重複處理 iterator.remove(); } } else { System.out.println("waiting……"); } } } catch (Exception e) { e.printStackTrace(); } finally { } } private void readData(SelectionKey key) { SocketChannel channel = null; try { channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int count = channel.read(buffer); if (count > 0) { String msg = new String(buffer.array()); System.out.println("from 客戶端 " + msg); //向其他客戶端轉發訊息 sendInfoToOtherClient(msg, channel); } } catch (IOException e) { try { System.out.println(channel.getRemoteAddress() + " 離線了"); key.cancel(); channel.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } // 轉發訊息給其他客戶(即通道) private void sendInfoToOtherClient(String msg, SocketChannel self) throws IOException { System.out.println("伺服器轉發訊息"); for (SelectionKey key : selector.keys()) { Channel targetChannel = key.channel(); if (targetChannel instanceof SocketChannel && targetChannel != self) { SocketChannel dest = (SocketChannel) targetChannel; ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); dest.write(buffer); } } } public static void main(String[] args) { GroupChatServer groupChatServer = new GroupChatServer(); groupChatServer.listen(); } }

GroupChatClient

package com.github.bjlhx15.netty.demo.groupchat;

import sun.jvm.hotspot.oops.ByteField;

import java.io.IOException;
import java.net.InetSocketAddress;
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.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {
    private final String HOST = "127.0.0.1";
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public GroupChatClient() throws IOException {
        selector = this.selector.open();
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok^……");
    }

    public void sendInfo(String info) {
        info = username + " 說:" + info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readInfo() {
        try {
            int readChannels = selector.select();
            if (readChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
//                    key.cancel();
                    iterator.remove();
                }
            } else {
//                System.out.println("沒有可用通道");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        GroupChatClient chatClient = new GroupChatClient();
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }.start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
轉載請註明出處,感謝。 作者:李巨集旭 出處:http://bjlhx.cnblogs.com 閱罷此文,如果您覺得本文不錯並有所收穫,請【打賞】或【推薦】,也可【評論】留下您的問題或建議與我交流。
你的支援是我不斷創作和分享的不竭動力!