java nio 消息,Java Nio 保持长连接分发消息(4)

当前位置:我的异常网» J2SE » Java Nio 保持长连接分发消息

Java Nio 保持长连接分发消息(4)

www.myexceptions.net  网友分享于:2015-08-26  浏览:287次

import java.nio.channels.Selector;

import java.nio.channels.SelectionKey;

import java.nio.channels.SelectableChannel;

import java.net.Socket;

import java.net.ServerSocket;

import java.net.InetSocketAddress;

import java.util.Iterator;

public class Server {

public static final int PORT=8033;

public static void main(String [] args) throws IOException{

Server s=new Server();

s.go();

}

private static ByteBuffer buff=ByteBuffer.allocateDirect(1024);

public void go() throws IOException {

ServerSocketChannel serverChannel=ServerSocketChannel.open();

ServerSocket serverSocket=serverChannel.socket();

serverSocket.bind(new InetSocketAddress(PORT));

System.out.println("server start to listen port"+PORT);

Selector selector =Selector.open();

serverChannel.configureBlocking(false);

serverChannel.register(selector, SelectionKey.OP_ACCEPT);

while (true){

int n=selector.select();

if(n==0){

continue;

}

else{

//   System.out.println(n+"complicated");

Iterator it =selector.selectedKeys().iterator();

while( it.hasNext()){

SelectionKey key=(SelectionKey) it.next();

if(key.isAcceptable()){

ServerSocketChannel server = (ServerSocketChannel) key.channel();

SocketChannel channel=server.accept();

registerChannel(selector, channel, SelectionKey.OP_READ);

sayHello(channel);

}

if (key.isReadable())

{

readDataFromSocket(key);

}

it.remove();

}

}

}

}

private void readDataFromSocket(SelectionKey key) throws IOException {

SocketChannel channel=(SocketChannel)key.channel();

int count =0;

buff.clear();

while((count=channel.read(buff))>0){

buff.flip();

while(buff.hasRemaining()){

channel.write(buff);

}

buff.clear();

}

if(count<0)

channel.close();

}

private void sayHello(SocketChannel channel) throws IOException {

buff.clear();

buff.put("hello\r\n".getBytes());

buff.flip();

channel.write(buff);

}

private void registerChannel(Selector selector, SocketChannel channel,

int opRead) throws IOException {

if(channel==null)

return;

channel.configureBlocking(false);

channel.register(selector, SelectionKey.OP_READ);

}

}

获得 SocketChannel 直接 注册感兴趣的事件就是了

------其他解决方案--------------------

文章评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值