当前位置:我的异常网» 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 直接 注册感兴趣的事件就是了
------其他解决方案--------------------
文章评论