1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
| package com.jhj.nio.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 listenChannel; private static final int PROT = 6667;
public GroupChatServer() { try { selector = Selector.open(); listenChannel=ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(PROT)); listenChannel.configureBlocking(false); listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) { e.printStackTrace(); } }
public void listen() { try { while (true) { int count = selector.select(); if (count > 0) { Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { SocketChannel sc = listenChannel.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); System.out.println(sc.getRemoteAddress() + "上线"); }
if (key.isReadable()) { readDate(key); } iterator.remove(); } } else { System.out.println("等待..."); } } } catch (Exception e) { e.printStackTrace(); } finally {
}
}
private void readDate(SelectionKey key) {
SocketChannel channel = null; try { channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); int count = channel.read(byteBuffer); if (count > 0) { String s = new String(byteBuffer.array()); System.out.println("from客户端:" + s);
sendInfoToOtherClients(s, channel); }
} catch (IOException e) {
try { System.out.println(channel.getRemoteAddress() + "离线了...."); key.cancel(); channel.close(); } catch (IOException ex) { ex.printStackTrace(); }
} }
private void sendInfoToOtherClients(String s, SocketChannel socketChannel) throws IOException {
System.out.println("服务器转发消息中"); for (SelectionKey key : selector.keys()) { Channel channel = key.channel(); if (channel instanceof SocketChannel && channel != socketChannel) { SocketChannel channel1 = (SocketChannel) channel; ByteBuffer wrap = ByteBuffer.wrap(s.getBytes()); channel1.write(wrap); } }
}
public static void main(String[] args) { GroupChatServer groupChatServer = new GroupChatServer(); groupChatServer.listen(); } }
|