服务器端

package com.ronnie.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 PORT = 9999; /* 构造器
初始化任务
*/
public GroupChatServer(){
try {
// 得到选择器
selector = Selector.open();
// serverSocketChannel
listenChannel = ServerSocketChannel.open();
// 绑定端口
listenChannel.socket().bind(new InetSocketAddress(PORT));
// 设置非阻塞模式
listenChannel.configureBlocking(false);
// 将该listenChannel 注册到Selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT); }catch (IOException e){
e.printStackTrace();
}
} /**
* 监听
*/
public void listen(){
try {
// 循环处理
while (true){
int count = selector.select(2000);
if (count > 0){ // 有事件处理
// 遍历得到的selectionKey集合
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
// 取出selectionKey
SelectionKey key = iterator.next(); // 监听到OP_ACCEPT
if (key.isAcceptable()){
SocketChannel sc = listenChannel.accept();
sc.configureBlocking(false);
// 将该socketChannel注册到Selector
sc.register(selector, SelectionKey.OP_READ);
// 提示
System.out.println(sc.getRemoteAddress() + " connected to the chat");
}
// 通道可读
if (key.isReadable()){
// TODO处理读
readData(key);
}
// 当前的key删除, 防止重复处理
iterator.remove();
}
} else {
System.out.println("Waiting......");
}
}
}catch (Exception e){
e.printStackTrace();
} finally {
// 发生异常处理
}
} /**
* 读取客户端消息
* @param key
*/
private void readData(SelectionKey key){
// 定义一个SocketChannel
SocketChannel channel = null;
try {
// 得到channel
channel = (SocketChannel) key.channel(); // 创建缓冲buffer
ByteBuffer buffer = ByteBuffer.allocate(1024); int count = channel.read(buffer);
// 根据count的值做处理
if (count > 0){
// 把缓冲区数据转为字符串并输出
String msg = new String(buffer.array());
// 输出该消息
System.out.println("from Client: " + msg); // 向其他的客户端转发消息(去掉自己)
sendInfoToOtherClients(msg,channel);
}
} catch (IOException e){
try {
System.out.println(channel.getRemoteAddress() + " is offline");
// 取消注册
key.cancel();
// 关闭通道
channel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} /**
* 转发消息给其他客户端(channel)
* @param msg
* @param self
*/
private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
System.out.println("Server is transferring messages......");
// 遍历, 所有注册到selector上的 SocketChannel, 并派出 自己
for (SelectionKey key : selector.keys()){ // 通过key取出对应的SocketChannel
Channel targetChannel = key.channel(); // 排除自己
if (targetChannel instanceof SocketChannel && targetChannel != self){ // 转型
SocketChannel dest = (SocketChannel) targetChannel; // 将消息存储到buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); // 将buffer数据写入到通道
dest.write(buffer);
}
}
} public static void main(String[] args) { // 创建服务器对象
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}

客户端

package com.ronnie.nio.groupChat;

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.SocketChannel;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner; public class GroupChatClient { // 定义相关属性 private final int PORT = 9999;
private Selector selector;
private SocketChannel socketChannel;
private java.lang.String username; /**
* 构造器, 完成初始化工作
*/
public GroupChatClient() throws IOException { selector = Selector.open(); // 连接服务器
socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT)); // 设置非阻塞
socketChannel.configureBlocking(false); // 将channel 注册到selector
socketChannel.register(selector, SelectionKey.OP_READ); // 得到username
username = socketChannel.getLocalAddress().toString().substring(1); System.out.println(username + " is fine"); } /**
* 向服务器发送消息
* @param info
*/
public void sendInfo(java.lang.String info){
info = username + " said: " + 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();
// 得到一个Buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 读取
sc.read(buffer);
// 把读到的缓冲区数据转成字符串
String msg = Arrays.toString((buffer.array()));
System.out.println(msg.trim());
}
}
iterator.remove(); // 删除当前的selectionKey, 防止重复操作
} else {
System.out.println("No channel available");
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws IOException { // 启动客户端
GroupChatClient chaClient = new GroupChatClient(); // 启动一个线程
new Thread(){
@Override
public void run() {
while (true){
chaClient.readInfo(); try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 发送数据给服务器端
Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){
String s = scanner.nextLine();
chaClient.sendInfo(s);
}
} }
  • PS: 这种代码不是天天敲是不可能很熟的, 只是找找感觉, 哪天真用到了回来看看以前的博客......

最新文章

  1. Android测试提升效率批处理脚本
  2. 从零开始学 Java - Spring MVC 统一异常处理
  3. php中ajax调用出错的问题
  4. 【Composer】实战操作一:使用库
  5. 分享一个TP5实现Create()方法的心得
  6. IOS 单例 创建方式
  7. iOS常见问题(5)
  8. 開始Unity3D的学习之旅
  9. Java计算当前日期前后几天是哪一天:
  10. Centos:如何查找安装的jdk的目录
  11. 基于udp的套接字编程
  12. unity 调整摄像机视角完整脚本
  13. C语言实现KMP模式匹配算法
  14. 007.基于Docker的Etcd分布式部署
  15. 最新2018年三月可用Windows10激活密钥
  16. poj 2253——Frogger
  17. 字母统计-map
  18. php curl curl_getinfo()返回参数详解
  19. override的实现原理
  20. java基础(三) 加强型for循环与Iterator

热门文章

  1. P1017进制转化
  2. 二十 Struts2的标签库,数据回显(基于值栈)
  3. rails work
  4. keil中的一些技巧
  5. Java - 实现双向链表
  6. $.fn.exted({})与$.extend({})区别
  7. 34 java 文件过滤 FileFilter
  8. react - get或set 取值函数
  9. C语言的常用的数据类型有哪些_所占字节分别是多少
  10. jetson nano 安装 snowboy 遇到的问题及处理