package com.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Set;
import com.util.String2Hex;
public class MyServer {
int port;
ServerSocketChannel channel4Accept;
Selector selector;
public MyServer(int port) throws IOException {
this.port=port;
channel4Accept = ServerSocketChannel.open();
channel4Accept.configureBlocking(false);
ServerSocket ss = channel4Accept.socket();
ss.bind(new InetSocketAddress(port));
selector = Selector.open();
channel4Accept.register(selector, SelectionKey.OP_ACCEPT);
}
public void run() throws IOException, InterruptedException, NoSuchAlgorithmException {
while(true) {
int nKeys = selector.select();
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
SelectionKey aKey=null;
while(it.hasNext()) {
aKey = it.next();
it.remove();
if(aKey.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) aKey.channel();
SocketChannel channel4Talk = ssc.accept();
if(channel4Talk == null)
continue;
channel4Talk.configureBlocking(false);
channel4Talk.register(selector, SelectionKey.OP_READ);
} else if(aKey.isReadable()) {
SocketChannel channel4Talk = (SocketChannel)aKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
int len=channel4Talk.read(buffer);
String msg = new String(buffer.array(),0,len);
System.out.println("receive message��"+msg);
MessageDigest md = MessageDigest.getInstance("md5");
md.update(msg.getBytes());
byte[] digest = md.digest();
String ret = String2Hex.byte2Hex(digest);
System.out.println("digest = "+ret);
buffer.clear();
buffer.put(ret.getBytes());
buffer.flip();
channel4Talk.write(buffer);
channel4Talk.close();
} else if(aKey.isWritable()) {
System.out.println("writable events...");
}
}
}
}
}
JAVA nio的一个简单的例子
需积分: 44 163 浏览量
2017-04-03
14:13:08
上传
评论
收藏 10KB RAR 举报
lhao_cn
- 粉丝: 1
- 资源: 8
最新资源
- 555springboot + vue 线上教学平台.zip(可运行源码+数据库文件+文档)
- 554springcloud + vue 房产销售平台.zip(可运行源码+数据库文件+文档)
- 小霸王坦克游戏源码.7z
- 蓝桥杯单片机基础学习项目(LED,数码管,蜂鸣器,继电器,按键控制)
- 553springboot + vue 某银行OA系统.zip(可运行源码+数据库文件+文档)
- DatabaseWatermarkingBasedonTextFormat
- yolov8常用二维码检测检测+数据集
- -移动通信-网络课程设计与研究
- 基于Python的PCA人脸识别算法的原理及实现代码+文档详解.zip
- 甘肃移动全业务工程建设项目管理流程优化研究
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈