socket selector

服务器:

  

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();
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值