轉自 http://blog.csdn.net/chenxuegui1234/article/details/17981203
好吧,承接上篇文章,下面給出一個udp不可靠無連接配接的例子,他的次傳送都是一個udp封包,不向上面文章中tcp是基于流的
代碼:
Server:
[java] view plain copy print ?
- 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 ?
- 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();
- }
- }