`
kingxss
  • 浏览: 969376 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java Socket学习笔记(五)- NIO UDP实践

阅读更多

一、回传协议接口和UDP方式实现:

1.接口:

import java.nio.channels.SelectionKey;
import java.io.IOException;

public interface EchoProtocol {
  void handleAccept(SelectionKey key) throws IOException;
  void handleRead(SelectionKey key) throws IOException;
  void handleWrite(SelectionKey key) throws IOException;
}

 2.实现:

import java.net.SocketAddress;
import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.io.IOException;

public class UDPEchoSelectorProtocol implements EchoProtocol {
    private static final int ECHOMAX = 255; // Maximum size of echo datagram

    static class ClientRecord {
        public SocketAddress clientAddress;
        public ByteBuffer buffer = ByteBuffer.allocate(ECHOMAX);
    }

    public void handleAccept(SelectionKey key) throws IOException {
        
    }

    public void handleRead(SelectionKey key) throws IOException {
        DatagramChannel channel = (DatagramChannel) key.channel();
        ClientRecord clntRec = (ClientRecord) key.attachment();
        clntRec.buffer.clear(); // Prepare buffer for receiving
        clntRec.clientAddress = channel.receive(clntRec.buffer);
        if (clntRec.clientAddress != null) { // Did we receive something?
            // Register write with the selector
            key.interestOps(SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        DatagramChannel channel = (DatagramChannel) key.channel();
        ClientRecord clntRec = (ClientRecord) key.attachment();
        clntRec.buffer.flip(); // Prepare buffer for sending
        int bytesSent = channel.send(clntRec.buffer, clntRec.clientAddress);
        if (bytesSent != 0) { // Buffer completely written?
            // No longer interested in writes
            key.interestOps(SelectionKey.OP_READ);
        }
    }

}

 

二、NIO UDP客户端:

import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class UDPEchoClientNonblocking {

    private static final int TIMEOUT = 3000; // Resend timeout (milliseconds)
    private static final int MAXTRIES = 255; // Maximum retransmissions
    
    public static void main(String args[]) throws Exception {
        // Convert input String to bytes using the default charset
        byte[] bytesToSend = "0123456789abcdefghijklmnopqrstuvwxyz".getBytes();

        // Create channel and set to nonblocking
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.configureBlocking(false);
        datagramChannel.socket().setSoTimeout(TIMEOUT);
        
        ByteBuffer writeBuf = ByteBuffer.wrap(bytesToSend);
        ByteBuffer readBuf = ByteBuffer.allocate(MAXTRIES);
        
        datagramChannel = datagramChannel.connect(new InetSocketAddress("127.0.0.1", 5500));

        int totalBytesRcvd = 0; // Total bytes received so far
        int bytesRcvd; // Bytes received in last read
        while (totalBytesRcvd < bytesToSend.length) {
            if (writeBuf.hasRemaining()) {
                datagramChannel.write(writeBuf);
            }
            if ((bytesRcvd = datagramChannel.read(readBuf)) == -1) {
                throw new SocketException("Connection closed prematurely");
            }
            totalBytesRcvd += bytesRcvd;
            System.out.print("."); // Do something else
        }

        System.out.println("Received: " + new String(readBuf.array(), 0, totalBytesRcvd));
        datagramChannel.close();
    }
}

 

三、NIO UDP服务端:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;

public class UDPEchoServerSelector {

    private static final int TIMEOUT = 3000; // Wait timeout (milliseconds)

    public static void main(String[] args) throws IOException {
        // Create a selector to multiplex client connections.
        Selector selector = Selector.open();

        DatagramChannel channel = DatagramChannel.open();
        channel.configureBlocking(false);
        channel.socket().bind(new InetSocketAddress(5500));
        channel.register(selector, SelectionKey.OP_READ, new UDPEchoSelectorProtocol.ClientRecord());

        UDPEchoSelectorProtocol echoSelectorProtocol = new UDPEchoSelectorProtocol();
        while (true) { // Run forever, receiving and echoing datagrams
            // Wait for task or until timeout expires
            if (selector.select(TIMEOUT) == 0) {
                System.out.print(".");
                continue;
            }

            // Get iterator on set of keys with I/O to process
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next(); // Key is bit mask

                // Client socket channel has pending data?
                if (key.isReadable())
                    echoSelectorProtocol.handleRead(key);

                // Client socket channel is available for writing and
                // key is valid (i.e., channel not closed).
                if (key.isValid() && key.isWritable())
                    echoSelectorProtocol.handleWrite(key);

                keyIter.remove();
            }
        }
    }

}

 

 

 参考:

1.《Java TCP/IP Socket编程(原书第2版)》

分享到:
评论

相关推荐

    Java Socket学习---nio实现阻塞多线程通信

    NULL 博文链接:https://1358440610-qq-com.iteye.com/blog/2115715

    基于java的开发源码-NIO网络框架 xSocket.zip

    基于java的开发源码-NIO网络框架 xSocket.zip 基于java的开发源码-NIO网络框架 xSocket.zip 基于java的开发源码-NIO网络框架 xSocket.zip 基于java的开发源码-NIO网络框架 xSocket.zip 基于java的开发源码-NIO网络...

    httpcore-nio-4.4.6-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.6.jar 赠送原API文档:httpcore-nio-4.4.6-javadoc.jar 赠送源代码:httpcore-nio-4.4.6-sources.jar 包含翻译后的API文档:httpcore-nio-4.4.6-javadoc-API文档-中文(简体)版.zip ...

    httpcore-nio-4.4.15-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.15.jar 赠送原API文档:httpcore-nio-4.4.15-javadoc.jar 赠送源代码:httpcore-nio-4.4.15-sources.jar 包含翻译后的API文档:httpcore-nio-4.4.15-javadoc-API文档-中文(简体)版....

    httpcore-nio-4.4.10-API文档-中英对照版.zip

    赠送jar包:httpcore-nio-4.4.10.jar; 赠送原API文档:httpcore-nio-4.4.10-javadoc.jar; 赠送源代码:httpcore-nio-4.4.10-sources.jar; 赠送Maven依赖信息文件:httpcore-nio-4.4.10.pom; 包含翻译后的API文档...

    xnio-nio-3.8.4.Final-API文档-中英对照版.zip

    赠送jar包:xnio-nio-3.8.4.Final.jar; 赠送原API文档:xnio-nio-3.8.4.Final-javadoc.jar; 赠送源代码:xnio-nio-3.8.4.Final-sources.jar; 赠送Maven依赖信息文件:xnio-nio-3.8.4.Final.pom; 包含翻译后的API...

    httpcore-nio-4.4.5-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.5.jar; 赠送原API文档:httpcore-nio-4.4.5-javadoc.jar; 赠送源代码:httpcore-nio-4.4.5-sources.jar; 赠送Maven依赖信息文件:httpcore-nio-4.4.5.pom; 包含翻译后的API文档:...

    Java Socket编程实例(五)- NIO UDP实践

    主要讲解Java Socket编程中NIO UDP的实例,希望能给大家做一个参考。

    httpcore-nio-4.4.10-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.10.jar; 赠送原API文档:httpcore-nio-4.4.10-javadoc.jar; 赠送源代码:httpcore-nio-4.4.10-sources.jar; 赠送Maven依赖信息文件:httpcore-nio-4.4.10.pom; 包含翻译后的API文档...

    httpcore-nio-4.3.jar包

    用Java实现非阻塞通信 ,用ServerSocket和Socket来编写服务器程序和客户程序,是Java网络编程的最基本的方式。 httpcore-nio-4.3.jar包

    httpcore-nio-4.4.15-API文档-中英对照版.zip

    赠送jar包:httpcore-nio-4.4.15.jar 赠送原API文档:httpcore-nio-4.4.15-javadoc.jar 赠送源代码:httpcore-nio-4.4.15-sources.jar 包含翻译后的API文档:httpcore-nio-4.4.15-javadoc-API文档-中文(简体)-...

    xnio-nio-3.8.4.Final-API文档-中文版.zip

    赠送jar包:xnio-nio-3.8.4.Final.jar; 赠送原API文档:xnio-nio-3.8.4.Final-javadoc.jar; 赠送源代码:xnio-nio-3.8.4.Final-sources.jar; 赠送Maven依赖信息文件:xnio-nio-3.8.4.Final.pom; 包含翻译后的API...

    xnio-nio-3.8.0.Final-API文档-中英对照版.zip

    赠送jar包:xnio-nio-3.8.0.Final.jar; 赠送原API文档:xnio-nio-3.8.0.Final-javadoc.jar; 赠送源代码:xnio-nio-3.8.0.Final-sources.jar; 赠送Maven依赖信息文件:xnio-nio-3.8.0.Final.pom; 包含翻译后的API...

    httpcore-nio-4.4.6-API文档-中英对照版.zip

    赠送jar包:httpcore-nio-4.4.6.jar; 赠送原API文档:httpcore-nio-4.4.6-javadoc.jar; 赠送源代码:httpcore-nio-4.4.6-sources.jar; 赠送Maven依赖信息文件:httpcore-nio-4.4.6.pom; 包含翻译后的API文档:...

    httpcore-nio-4.4.14-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.14.jar; 赠送原API文档:httpcore-nio-4.4.14-javadoc.jar; 赠送源代码:httpcore-nio-4.4.14-sources.jar; 赠送Maven依赖信息文件:httpcore-nio-4.4.14.pom; 包含翻译后的API文档...

    Java-NIO-Netty框架学习

    Java-NIO-Netty框架入门学习。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

    xnio-nio-3.8.0.Final-API文档-中文版.zip

    赠送jar包:xnio-nio-3.8.0.Final.jar; 赠送原API文档:xnio-nio-3.8.0.Final-javadoc.jar; 赠送源代码:xnio-nio-3.8.0.Final-sources.jar; 赠送Maven依赖信息文件:xnio-nio-3.8.0.Final.pom; 包含翻译后的API...

    Java-NIO-Programming-Cookbook(含源码)

    Java-NIO-Programming-Cookbook英文版和配套源代码。有一个使用DirectByteBuffer和Non-Direct Buffer文件读取速度的对比实验程序和测试结果。

    jsch-nio, 通过SSH实现 Java nio 文件系统.zip

    jsch-nio, 通过SSH实现 Java nio 文件系统 jsch-nio注意,这个项目依赖于 jsch扩展插件项目JSch是利用JSch实现实现一个 nio 文件系统,以及它随之一起运行的所有方法。 到目前为止,有一个功能齐全的unix/linux ...

Global site tag (gtag.js) - Google Analytics