程序是通了,但是没法转发,获取不到对方ip。nio中 udp使用的是DatagramChannel ,但是SelectorKey.channel()转化之后的DatagramChannel,调用getRemoteAddress()获取不到对方的ip信息。

看了下java doc

A selectable channel for datagram-oriented sockets.

A datagram channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing datagram socket. A newly-created datagram channel is open but not connected. A datagram channel need not be connected in order for the send and receive methods to be used. A datagram channel may be connected, by invoking its connect method, in order to avoid the overhead of the security checks are otherwise performed as part of every send and receive operation. A datagram channel must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses.

Once connected, a datagram channel remains connected until it is disconnected or closed. Whether or not a datagram channel is connected may be determined by invoking its isConnected method.

更多信息点这里

这个意思差不多就是DatagramChannel 是面向数据报的,是无连接的,所以不需要知道对面ip。然后就为null了。

但是

在bio中,通过DatagramPacket 是可以获取到对方ip信息的。 所以 ip信息应该是在报文里了。所以我要怎么样才能从报文中拿到这个ip呢?

假如使用nio,默认必须要通过ByteBuf 去读取,这样子就获取不到完整的报文信息了。我服了!

以下是代码

  1. public class Server {
  2. private static LinkedList<SocketAddress> list=new LinkedList<SocketAddress>();
  3. private static final ExecutorService executorService = Executors.newFixedThreadPool(4);
  4. private static DatagramChannel server=null;
  5. private static Selector selector=null;
  6. static {
  7. try{
  8. server=DatagramChannel.open().bind(new InetSocketAddress(8889));
  9. server.configureBlocking(false);
  10. selector=Selector.open();
  11. }catch (Exception e){
  12. e.printStackTrace();
  13. }
  14. }
  15. public static void main(String[] args)throws Exception {
  16. server.register(selector, SelectionKey.OP_READ);
  17. while (true){
  18. if (selector.select()>0){
  19. Set<SelectionKey> keys = selector.selectedKeys();
  20. Iterator<SelectionKey> iterator = keys.iterator();
  21. while (iterator.hasNext()){
  22. SelectionKey selectionKey = iterator.next();
  23. if (selectionKey.isReadable()){
  24. saveIP(selectionKey);
  25. String msg = readMsg(selectionKey);
  26. broadcast(msg);
  27. }
  28. iterator.remove();
  29. }}
  30. }
  31. }
  32. public static void saveIP(SelectionKey selectionKey)throws Exception{
  33. if (selectionKey.channel() instanceof DatagramChannel){
  34. System.out.println(true);
  35. }
  36. DatagramChannel channel=(DatagramChannel)selectionKey.channel();
  37. SocketAddress address = channel.getRemoteAddress();
  38. if (!list.contains(address)){
  39. list.add(address);
  40. System.out.println("新增ip:"+address);
  41. }
  42. System.out.println("当前udp 保存的ip数量:"+list.size());
  43. }
  44. public static void broadcast(String msg) throws Exception{
  45. ByteBuffer byteBuffer=ByteBuffer.wrap(msg.getBytes());
  46. //DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length);
  47. for (SocketAddress address:list
  48. ) {
  49. executorService.submit(new Runnable() {
  50. @Override
  51. public void run() {
  52. try{
  53. server.send(byteBuffer,address);
  54. }catch (Exception e){
  55. System.out.println(Thread.currentThread().getName()+":"+address+"发送失败");
  56. }
  57. }
  58. });
  59. }
  60. }
  61. public static String readMsg(SelectionKey selectionKey)throws Exception{
  62. DatagramChannel channel=(DatagramChannel)selectionKey.channel();
  63. ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
  64. channel.receive(byteBuffer);
  65. byteBuffer.flip();
  66. String msg=new String(byteBuffer.array(),"utf-8");
  67. System.out.println("收到消息:"+msg);
  68. return msg;
  69. }
  70. }

####已经找到解决办法了
DatagramChannel的 receive方法的返回值就是发送端的ip
> public abstract SocketAddress receive(ByteBuffer dst) throws IOException
Receives a datagram via this channel.
If a datagram is immediately available, or if this channel is in blocking mode and one eventually becomes available, then the datagram is copied into the given byte buffer and its source address is returned. If this channel is in non-blocking mode and a datagram is not immediately available then this method immediately returns null.
The datagram is transferred into the given byte buffer starting at its current position, as if by a regular read operation. If there are fewer bytes remaining in the buffer than are required to hold the datagram then the remainder of the datagram is silently discarded.
This method performs exactly the same security checks as the receive method of the DatagramSocket class. That is, if the socket is not connected to a specific remote address and a security manager has been installed then for each datagram received this method verifies that the source's address and port number are permitted by the security manager's checkAccept method. The overhead of this security check can be avoided by first connecting the socket via the connect method.
This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete. If this channel's socket is not bound then this method will first cause the socket to be bound to an address that is assigned automatically, as if invoking the bind method with a parameter of null.
Parameters:
dst - The buffer into which the datagram is to be transferred
Returns:
The datagram's source address, or null if this channel is in non-blocking mode and no datagram was immediately available //这里说了,返回值是source address
Throws:
ClosedChannelException - If this channel is closed
AsynchronousCloseException - If another thread closes this channel while the read operation is in progress
ClosedByInterruptException - If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt status
SecurityException - If a security manager has been installed and it does not permit datagrams to be accepted from the datagram's sender
IOException - If some other I/O error occurs

JAVA NIO 获取udp数据报的 发送方ip的更多相关文章

  1. Java网络编程(UDP协议:发送端)

    package WebProgramingDemo; import java.io.IOException; import java.net.DatagramPacket; import java.n ...

  2. linux下的shell命令的编写,以及java怎样调用linux的shell命令(java怎样获取linux上的网卡的ip信息)

    程序猿都非常懒,你懂的! 近期在开发中,须要用到server的ip和mac信息.可是server是架设在linux系统上的,对于多网口,在获取ip时就产生了非常大的问题.以下是在windows系统上, ...

  3. Java里面获取当前服务器(linux环境)的IP地址--与请求者的真实IP

    package com.wfd360.Util; import javax.servlet.http.HttpServletRequest; import java.net.Inet4Address; ...

  4. 消息中间件系列三:使用RabbitMq原生Java客户端进行消息通信(消费者(接收方)自动确认模式、消费者(接收方)自行确认模式、生产者(发送方)确认模式)

    准备工作: 1)安装RabbitMQ,参考文章:消息中间件系列二:RabbitMQ入门(基本概念.RabbitMQ的安装和运行) 2.)分别新建名为OriginalRabbitMQProducer和O ...

  5. Java网络编程UDP通信原理

    前言 继续今天我们的Java网络编程--TCP和UDP通信 一.TCP和UDP概述 传输层通常以TCP和UDP协议来控制端点与端点的通信   TCP UDP 协议名称 传输控制协议 用户数据包协议 是 ...

  6. Java NIO UDP DEMO

    今天有人问我Netty的UDP怎么使用,我自己尝试的去写一个Demo,在网上搜索了一下,关于Netty的UDP实现还是很少的,所以,今天写下这篇文章用来记录今天的一个简单Demo实现 不使用Netty ...

  7. 使用JAVA NIO实现的UDP client和server

    //////////////////////////////////////////////////////////////////////////////////////////////////// ...

  8. JAVA NIO异步通信框架MINA选型和使用的几个细节(概述入门,UDP, 心跳)

    Apache MINA 2 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架.它提供了一个抽象的事件驱动的异步 API,可以使用 TCP/IP.UDP/IP.串口和虚拟机内部的管道等传输方式.A ...

  9. JAVA中获取当前运行的类名,方法名,行数

    JAVA中获取当前运行的类名,方法名,行数 public static String getTraceInfo(){ StringBuffer sb = new StringBuffer(); Sta ...

随机推荐

  1. OpenGL在ubuntu下的成功配置

    sudo apt-get update sudo apt-get install build-essential sudo apt-get install libgl1-mesa-dev sudo a ...

  2. 使用.NET Core中创建Windows服务(一) - 使用官方推荐方式

    原文:Creating Windows Services In .NET Core – Part 1 – The "Microsoft" Way 作者:Dotnet Core Tu ...

  3. Java基础学习笔记(二) - 面向对象基础

    面向对象 一.面向对象概述 面向对象思想就是在计算机程序设计过程中,参照现实事物,将事物的属性特征.行为特征抽象出来,描述成计算机时间的设计思想.面向对象思想区别于面向过程思想,强调的是通过调用对象的 ...

  4. DevExpress GridControl导出ExportToXls 数字类型显示成货币格式

    用Dev开发很习惯直接用自带控件导出Excel,现在很少使用原生的Excel API去操作了.除非需要详细的控制. 但别人家封装好的就得按人家的规则的.在使用GridControl导出Excel时发现 ...

  5. CentOS7下mongodb忘记密码后重置密码

    新装mongodb后,结果一段时间没有用,密码给忘记了,只能重置密码了. 步骤如下: 1.找到mongodb的配置文件 通过ps -ef|grep mongod找到mongodb的配置文件mongod ...

  6. linux分析工具之vmstat详解

    一.概述 vmstat命令是最常见的Linux/Unix监控工具,可以展现给定时间间隔的服务器的状态值,包括服务器的CPU使用率,内存使用,虚拟内存交换情况,IO读写情况.首先我们查看下帮助.如下图所 ...

  7. Siege 网站性能压力测试工具使用入门

    Siege is an open source regression test and benchmark utility. It can stress test a single URL with ...

  8. 分享8点超级有用的Python编程建议

    我们在用Python进行机器学习建模项目的时候,每个人都会有自己的一套项目文件管理的习惯,我自己也有一套方法,是自己曾经踩过的坑总结出来的,现在在这里分享一下给大家,希望多少有些地方可以给大家借鉴.

  9. Android 横竖屏切换生命周期

    默认情况下,屏幕会旋转并且会重新走生命周期. 1. 屏幕不旋转   在AndroidManifest文件中的对应Activity中配置android:screenOrientation=”landsc ...

  10. java工具类之Arrays、Collections以及比较器

    一.Comparable和Comparator的详解 Comparable & Comparator 都是用来实现集合中元素的比较.排序的,只是 Comparable 是在集合内部定义的方法实 ...