您的位置:首页 > 编程语言 > Java开发

Java NIO——6 基于非阻塞编程UDP NIO的例子

2016-08-20 17:26 387 查看
转自 http://blog.csdn.net/chenxuegui1234/article/details/17981203

好吧,承接上篇文章,下面给出一个udp不可靠无连接的例子,他的次传送都是一个udp报文,不向上面文章中tcp是基于流的

代码:

Server:

[java] view
plain copy

 print?

/** 

 * 服务器端 

 *  

 * @author Joeson 

 *  

 */  

public class UDPServer  

{  

    DatagramChannel channel;  

  

    Selector selector;  

  

    public void work()  

    {  

        try  

        {  

            // 打开一个UDP Channel  

            channel = DatagramChannel.open();  

  

            // 设定为非阻塞通道  

            channel.configureBlocking(false);  

            // 绑定端口  

            channel.socket().bind(new InetSocketAddress(8080));  

  

            // 打开一个选择器  

            selector = Selector.open();  

            channel.register(selector, SelectionKey.OP_READ);  

        } catch (Exception e)  

        {  

            e.printStackTrace();  

        }  

  

        ByteBuffer byteBuffer = ByteBuffer.allocate(65536);  

        while (true)  

        {  

            try  

            {  

                // 进行选择  

                int n = selector.select();  

                if (n > 0)  

                {  

                    // 获取以选择的键的集合  

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

  

                    while (iterator.hasNext())  

                    {  

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

  

                        // 必须手动删除  

                        iterator.remove();  

  

                        if (key.isReadable())  

                        {  

                            DatagramChannel datagramChannel = (DatagramChannel) key  

                                    .channel();  

  

                            byteBuffer.clear();  

                            // 读取  

                            InetSocketAddress address = (InetSocketAddress) datagramChannel  

                                    .receive(byteBuffer);  

  

                            System.out.println(new String(byteBuffer.array()));  

  

                            // 删除缓冲区中的数据  

                            byteBuffer.clear();  

  

                            String message = "data come from server";  

  

                            byteBuffer.put(message.getBytes());  

  

                            byteBuffer.flip();  

  

                            // 发送数据  

                            datagramChannel.send(byteBuffer, address);  

                        }  

                    }  

                }  

            } catch (Exception e)  

            {  

                e.printStackTrace();  

            }  

        }  

  

    }  

  

    public static void main(String[] args)  

    {  

        new UDPServer().work();  

  

    }  

  

}  

客户端:

[java] view
plain copy

 print?

/** 

 * 客户端 

 *  

 * @author Joeson 

 */  

public class UDPClient  

{  

    DatagramChannel channel;  

    Selector selector;  

  

    public void work()  

    {  

  

        try  

        {  

            // 开启一个通道  

            channel = DatagramChannel.open();  

  

            channel.configureBlocking(false);  

  

            SocketAddress sa = new InetSocketAddress("localhost", 8080);  

  

            channel.connect(sa);  

        } catch (Exception e)  

        {  

            e.printStackTrace();  

        }  

  

        try  

        {  

            selector = Selector.open();  

            channel.register(selector, SelectionKey.OP_READ);  

            channel.write(Charset.defaultCharset().encode("data come from client"));  

        } catch (Exception e)  

        {  

            e.printStackTrace();  

        }  

  

        ByteBuffer byteBuffer = ByteBuffer.allocate(100);  

        while (true)  

        {  

            try  

            {  

                int n = selector.select();  

                if (n > 0)  

                {  

  

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

  

                    while (iterator.hasNext())  

                    {  

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

                        iterator.remove();  

                        if (key.isReadable())  

                        {  

                            channel = (DatagramChannel) key.channel();  

                            channel.read(byteBuffer);  

  

                            System.out.println(new String(byteBuffer.array()));  

                              

                              

                            byteBuffer.clear();  

                              

                            channel.write(Charset.defaultCharset().encode(  

                                    "data come from client"));  

                        }  

                    }  

                }  

            } catch (Exception e)  

            {  

                e.printStackTrace();  

            }  

        }  

  

    }  

  

    public static void main(String[] args)  

    {  

        new UDPClient().work();  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: