服务器:
package com.road.selectsocket;
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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class GameServer implements Runnable{
private Selector selector;
private ServerSocketChannel servChannel;
private volatile boolean stop = false;
public GameServer(int port)
{
try {
selector = Selector.open();
servChannel = ServerSocketChannel.open();
servChannel.configureBlocking(false);
servChannel.socket().bind(new InetSocketAddress(port),1024);
servChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("GameServer start in "+ port);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(!stop)
{
try {
selector.select(1000);
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
SelectionKey key = null;
while(it.hasNext())
{
key = it.next();
it.remove();
try {
handlerInput(key);
} catch (Exception e) {
if(key!=null)
{
key.cancel();
if(key.channel()!=null)
{
key.channel().close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(selector!=null)
{
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handlerInput(SelectionKey key) throws IOException
{
if(key.isValid())
{
if(key.isAcceptable())
{
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
try {
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
}
if(key.isReadable())
{
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(readBuffer);
if(readBytes>0)
{
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body = new String(bytes,"UTF-8");
System.out.println("rece:"+body);
doWrite(sc,"hello world");
}
else if(readBytes<0)
{
key.cancel();
sc.close();
}
else
{
; //读到0字节
}
}
}
}
private void doWrite(SocketChannel sc,String content) throws IOException
{
if(content!=null && content.trim().length()>0)
{
byte[] bytes = content.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
sc.write(writeBuffer);
}
}
public static void main(String[] args)
{
int port = 9200;
GameServer server = new GameServer(port);
new Thread(server,"nio-select").start();
}
}
客户端
package com.road.selectsocket;
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.Set;
public class GameClient implements Runnable{
private String host;
private int port;
private Selector selector;
private SocketChannel channel;
private volatile boolean stop=false;
public GameClient(String host,int port)
{
this.host = host;
this.port = port;
try {
selector = Selector.open();
channel = SocketChannel.open();
channel.configureBlocking(false);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
doConnect();
} catch (IOException e) {
e.printStackTrace();
}
while(!stop)
{
SelectionKey key = null;
try {
selector.select(1000);
Set<SelectionKey> keys = selector.selectedKeys();
java.util.Iterator<SelectionKey> it = keys.iterator();
while(it.hasNext())
{
key = it.next();
it.remove();
handlerInput(key);
}
}
catch (IOException e) {
if(key!=null)
{
key.cancel();
if(key.channel()!=null)
{
try {
key.channel().close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
e.printStackTrace();
}
}
if(selector!=null)
{
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handlerInput(SelectionKey key) throws IOException
{
if(key.isValid())
{
if(key.isConnectable())
{
SocketChannel sc = (SocketChannel) key.channel();
if(sc.finishConnect())
{
sc.register(selector, SelectionKey.OP_READ);
doWrite(sc,"hello world222");
}
}
if(key.isReadable())
{
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(readBuffer);
if(readBytes>0)
{
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body = new String(bytes,"UTF-8");
System.out.println("rece:"+body);
//doWrite(sc,"hello world11");
}
else if(readBytes<0)
{
key.cancel();
sc.close();
}
else
{
; //读到0字节
}
}
}
}
private void doConnect() throws IOException
{
if(channel.connect(new InetSocketAddress(host,port))){
channel.register(selector,SelectionKey.OP_READ);
doWrite(channel,"hello2222");
}
else
{
channel.register(selector,SelectionKey.OP_CONNECT);
}
}
private void doWrite(SocketChannel sc,String content) throws IOException
{
if(content!=null && content.trim().length()>0)
{
byte[] bytes = content.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
sc.write(writeBuffer);
}
}
public static void main(String[] args)
{
GameClient client = new GameClient("127.0.0.1",9200);
new Thread(client,"nio-clientSelect").start();
}
}