import java.nio.channels.*;
import java.nio.charset.*;
import java.nio.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class NBlockingServer {
int port = 8000;
int BUFFERSIZE = 1024;
Selector selector = null;
ServerSocketChannel serverChannel = null;
HashMap clientChannelMap = null; //用来存放每一个客户连接对应的套接字和通道
public NBlockingServer(int port) {
this.clientChannelMap = new HashMap();
this.port = port;
}
//throws IOException
public void initialize() {
//初始化,分别实例化一个选择器,一个服务器端可选择通道
try {
this.selector = Selector.open();
this.serverChannel = ServerSocketChannel.open();
this.serverChannel.configureBlocking(false);
InetAddress localhost = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(localhost, this.port);
this.serverChannel.socket().bind(isa); //将该套接字绑定到服务器某一可用端口
}
catch (IOException ex) {
}
}
//结束时释放资源 throws IOException
public void finalize() {
try {
this.serverChannel.close();
this.selector.close();
}
catch (IOException ex) {
}
}
//监听端口,当通道准备好时进行相应操作 throws IOException, InterruptedException
public void portListening() {
//服务器端通道注册OP_ACCEPT事件
try {
SelectionKey acceptKey = this.serverChannel.register(this.selector,
SelectionKey.OP_ACCEPT);
//当有(已注册的事件)发生时,select()返回值将大于0
while (acceptKey.selector().select() > 0) {
//System.out.println("event happened");
//取得所有已经准备好的所有选择键
Set readyKeys = this.selector.selectedKeys();
//使用迭代器对选择键进行轮询
Iterator i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
i.remove(); //删除当前将要处理的选择键
if (key.isAcceptable()) { //如果是有客户端连接请求
System.out.println("more client connect in!");
ServerSocketChannel nextReady = (ServerSocketChannel) key.channel();
SocketChannel sc = (SocketChannel) nextReady.accept();
//获取客户端套接字
//Socket s = nextReady.accept().socket();
Socket s = sc.socket();
//SocketChannel s = nextReady.accept();
//设置对应的通道为异步方式并注册感兴趣事件
//SocketChannel schannel=(SocketChannel)s.getChannel();
s.getChannel().configureBlocking(false);
//SelectionKey readWriteKey =s.getChannel().register(this.selector,SelectionKey.OP_READ |SelectionKey.OP_WRITE);
SelectionKey readWriteKey = s.getChannel().register(this.selector,
SelectionKey.OP_READ);
//将注册的事件与该套接字联系起来
readWriteKey.attach(s); //将给定的对象附加到此键。
//将当前建立连接的客户端套接字及对应的通道存放在哈希表//clientChannelMap中
this.clientChannelMap.put(s, new ClientChInstance(s.getChannel()));
}
else if (key.isReadable()) { //如果是通道读准备好事件
System.out.println("Readable");
//取得选择键对应的通道和套接字
SelectableChannel nextReady = (SelectableChannel) key.channel();
Socket socket = (Socket) key.attachment(); //// 检索当前的附加对象。
//处理该事件,处理方法已封装在类ClientChInstance中
this.readFromChannel(socket.getChannel(),
(ClientChInstance)this.
clientChannelMap.get(socket));
}
else if (key.isWritable()) { //如果是通道写准备好事件
System.out.println("writeable");
//取得套接字后处理,方法同上
Socket socket = (Socket) key.attachment(); // 检索当前的附加对象。
SocketChannel channel = (SocketChannel) socket.getChannel();
this.writeToChannel(channel, "This is from server!");
}
}
}
}
catch (ClosedChannelException ex) {
}
catch (IOException ex) {
}
}
//对通道的写操作
public void writeToChannel(SocketChannel channel, String message) {
try {
ByteBuffer buf = ByteBuffer.wrap(message.getBytes("gb2312"));
int nbytes = channel.write(buf);
}
catch (IOException ex) {
System.out.println("系统向客户端发送数据出错;");
}
}
//将读入字节缓冲的信息解码
public String decode(ByteBuffer byteBuffer) throws
CharacterCodingException {
Charset charset = Charset.forName("gb2312");
CharsetDecoder decoder = charset.newDecoder(); //为此 charset 构造新的解码器。
CharBuffer charBuffer = decoder.decode(byteBuffer); // 把单个输入字节缓冲区的剩余内容解码到新分配的字符缓冲区的便捷方法。
String result = charBuffer.toString(); //
return result;
}
//对通道的读操作throws IOException, InterruptedException
public void readFromChannel(SocketChannel channel,ClientChInstance clientInstance) {
try {
ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFERSIZE);
int nbytes = channel.read(byteBuffer); //断开是出错
//System.out.println(nbytes);
byteBuffer.flip();
String result = this.decode(byteBuffer);
//当客户端发出”@exit”退出命令时,关闭其通道
if (result.indexOf("@exit") >= 0) {
channel.close();
System.out.println("客户端关闭");
}
else {
clientInstance.append(result.toString());
//读入一行完毕,执行相应操作
//if (result.indexOf("\n") >= 0) {
System.out.println("client input" + result);
clientInstance.execute();
//}
}
}
catch (IOException ex) {
try {
channel.close();
}
catch (IOException ex1) {
}
}
}
//该类封装了怎样对客户端的通道进行操作,具体实现可以通过重载execute()方法
public class ClientChInstance {
SocketChannel channel;
MessageData mdata; //业务处理模块
StringBuffer buffer = new StringBuffer();
public ClientChInstance(SocketChannel channel) {
this.channel = channel;
this.mdata= new MessageData();
}
public void execute() {
//String message = "AAA00100311111111000001100000200707161008220033 99999999hello,welcomd!this is 请求连接 first send.\n";
String info=buffer.toString();
String reinfo=mdata.isRigthData(info);
System.out.println("系统向客户端发送信息:"+reinfo);
if(reinfo!=null){
writeToChannel(this.channel, reinfo);
}
buffer = new StringBuffer();
}
//当一行没有结束时,将当前字窜置于缓冲尾
public void append(String values) {
buffer.append(values);
//mdata=new MessageData(this);
}
}
//主程序
public static void main(String[] args) {
NBlockingServer nbServer = new NBlockingServer(8000);
try {
nbServer.initialize();
}
catch (Exception e) {
e.printStackTrace();
System.exit( -1);
}
try {
nbServer.portListening();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
分享到:
相关推荐
1.采用重叠I/O方式实现的socket网络编程,异步非阻塞方式,代码效率比阻塞式的socket编程方式高。2.实现了TCP server方式,只用于服务端,可以支持多客户端。3.可以使用在各种场合用于监控网络数据。4.代码封装成库...
1. Socket 机制 Socket,又称为套接字,用于描述 IP 地址和...只要有 IO,就会有阻塞或非阻塞的问题,无论这个 IO 是网络的,还是硬盘的。原因在于程序是运行在系统之上的,任何形式的IO 操作发起都需要系统内核的支持。
javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...
javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...
javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...
Java非对称加密源程序代码实例,本例中使用RSA加密技术,定义加密算法可用 DES,DESede,Blowfish等。 设定字符串为“张三,你好,我是李四” 产生张三的密钥对(keyPairZhang) 张三生成公钥(publicKeyZhang...
Java非对称加密源程序代码实例,本例中使用RSA加密技术,定义加密算法可用 DES,DESede,Blowfish等。 设定字符串为“张三,你好,我是李四” 产生张三的密钥对(keyPairZhang) 张三生成公钥(publicKeyZhang...
第十二章 非阻塞I/O 391 一个示例客户端 392 一个示例服务器 396 缓冲区 402 通道 421 就绪选择 427 第十三章 UDP数据报和Socket 431 UDP协议 431 DatagramPacket类 433 DatagramSocket类 442 一些有用的...
程的基础知识、套接字编程、非阻塞通信、创建HTTP服务器与客户程序、 数据报通信、对象的序列化与反序列化、Java反射机制、RMI框架、JDBC API、JavaMail API、MVC设计模式、安全网络通信、CORBA和Web服务。另 外...
一个基于Java 1.4的NIO套接字框架。 这对开发人员隐藏了非阻塞IO的(肮脏的)细节,使他们能够轻松地构建高度可扩展的应用程序,该应用程序仅使用一个线程即可处理10000个以上的传入和传出套接字。
非阻塞连接服务端要启动多少个线程处理,在MyServerSocketModel实例化时自己修改参数 13.修改客户端,在连接失败后取消关联,使其连接失败后,可以再次连接不再阻塞 9.改用SocketChannel非阻塞模式
是围绕异步、非阻塞和事件驱动的交互设计的。 这允许您在使用相对较少数量的操作系统线程的同时为大量并发客户端提供服务。 使用 Socket.x 构建的应用程序已实现每个节点超过 1,000,000 个连接。 为了把事情放在上下...
Java高级程序设计测试含答案 Java高级程序设计测试含答案 您的姓名: [填空题] * _________________________________ Spring中将散落在系统中的共性问题集中解决的方案是()。 [单选题] * A. DI B. AOP(正确答案) C...
第十二章 非阻塞I/O 391 一个示例客户端 392 一个示例服务器 396 缓冲区 402 通道 421 就绪选择 427 第十三章 UDP数据报和Socket 431 UDP协议 431 DatagramPacket类 433 DatagramSocket类 442 一些有用的...
第十二章 非阻塞I/O 391 一个示例客户端 392 一个示例服务器 396 缓冲区 402 通道 421 就绪选择 427 第十三章 UDP数据报和Socket 431 UDP协议 431 DatagramPacket类 433 DatagramSocket类 442 一些有用的...
第十二章 非阻塞I/O 391 一个示例客户端 392 一个示例服务器 396 缓冲区 402 通道 421 就绪选择 427 第十三章 UDP数据报和Socket 431 UDP协议 431 DatagramPacket类 433 DatagramSocket类 442 一些有用的...