JAVA NIO 获取udp数据报的 发送方ip
程序是通了,但是没法转发,获取不到对方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 去读取,这样子就获取不到完整的报文信息了。我服了!
以下是代码
public class Server {
private static LinkedList<SocketAddress> list=new LinkedList<SocketAddress>();
private static final ExecutorService executorService = Executors.newFixedThreadPool(4);
private static DatagramChannel server=null;
private static Selector selector=null;
static {
try{
server=DatagramChannel.open().bind(new InetSocketAddress(8889));
server.configureBlocking(false);
selector=Selector.open();
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
server.register(selector, SelectionKey.OP_READ);
while (true){
if (selector.select()>0){
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if (selectionKey.isReadable()){
saveIP(selectionKey);
String msg = readMsg(selectionKey);
broadcast(msg);
}
iterator.remove();
}}
}
}
public static void saveIP(SelectionKey selectionKey)throws Exception{
if (selectionKey.channel() instanceof DatagramChannel){
System.out.println(true);
}
DatagramChannel channel=(DatagramChannel)selectionKey.channel();
SocketAddress address = channel.getRemoteAddress();
if (!list.contains(address)){
list.add(address);
System.out.println("新增ip:"+address);
}
System.out.println("当前udp 保存的ip数量:"+list.size());
}
public static void broadcast(String msg) throws Exception{
ByteBuffer byteBuffer=ByteBuffer.wrap(msg.getBytes());
//DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length);
for (SocketAddress address:list
) {
executorService.submit(new Runnable() {
@Override
public void run() {
try{
server.send(byteBuffer,address);
}catch (Exception e){
System.out.println(Thread.currentThread().getName()+":"+address+"发送失败");
}
}
});
}
}
public static String readMsg(SelectionKey selectionKey)throws Exception{
DatagramChannel channel=(DatagramChannel)selectionKey.channel();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
channel.receive(byteBuffer);
byteBuffer.flip();
String msg=new String(byteBuffer.array(),"utf-8");
System.out.println("收到消息:"+msg);
return msg;
}
}
####已经找到解决办法了
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的更多相关文章
- Java网络编程(UDP协议:发送端)
package WebProgramingDemo; import java.io.IOException; import java.net.DatagramPacket; import java.n ...
- linux下的shell命令的编写,以及java怎样调用linux的shell命令(java怎样获取linux上的网卡的ip信息)
程序猿都非常懒,你懂的! 近期在开发中,须要用到server的ip和mac信息.可是server是架设在linux系统上的,对于多网口,在获取ip时就产生了非常大的问题.以下是在windows系统上, ...
- Java里面获取当前服务器(linux环境)的IP地址--与请求者的真实IP
package com.wfd360.Util; import javax.servlet.http.HttpServletRequest; import java.net.Inet4Address; ...
- 消息中间件系列三:使用RabbitMq原生Java客户端进行消息通信(消费者(接收方)自动确认模式、消费者(接收方)自行确认模式、生产者(发送方)确认模式)
准备工作: 1)安装RabbitMQ,参考文章:消息中间件系列二:RabbitMQ入门(基本概念.RabbitMQ的安装和运行) 2.)分别新建名为OriginalRabbitMQProducer和O ...
- Java网络编程UDP通信原理
前言 继续今天我们的Java网络编程--TCP和UDP通信 一.TCP和UDP概述 传输层通常以TCP和UDP协议来控制端点与端点的通信 TCP UDP 协议名称 传输控制协议 用户数据包协议 是 ...
- Java NIO UDP DEMO
今天有人问我Netty的UDP怎么使用,我自己尝试的去写一个Demo,在网上搜索了一下,关于Netty的UDP实现还是很少的,所以,今天写下这篇文章用来记录今天的一个简单Demo实现 不使用Netty ...
- 使用JAVA NIO实现的UDP client和server
//////////////////////////////////////////////////////////////////////////////////////////////////// ...
- JAVA NIO异步通信框架MINA选型和使用的几个细节(概述入门,UDP, 心跳)
Apache MINA 2 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架.它提供了一个抽象的事件驱动的异步 API,可以使用 TCP/IP.UDP/IP.串口和虚拟机内部的管道等传输方式.A ...
- JAVA中获取当前运行的类名,方法名,行数
JAVA中获取当前运行的类名,方法名,行数 public static String getTraceInfo(){ StringBuffer sb = new StringBuffer(); Sta ...
随机推荐
- 安装vue开发环境
每次搜索vue开发环境安装时,总是有很多种版本,虽然都能安装完成,但还是整理下自己觉得比较好的版本吧 1.首先安装nodeJs以及也把git安装好(反正开发也是需要git),安装完成后执行 node ...
- linux 的vi/vim消除查找到的高亮字符串
方法如下: 在Vi里面如果要搜索某个关键字,只要键入/xxx就可以了,比如,要搜索一个函数,就键入/snprintf 然后回车,一个文件中,所有出现这个字样的地方都会被高亮显示.按n键,就可以自动把光 ...
- 【爬虫小程序:爬取斗鱼所有房间信息】Xpath(多线程版)
# 本程序亲测有效,用于理解爬虫相关的基础知识,不足之处希望大家批评指正 from queue import Queue import requests from lxml import etree ...
- httpSession和Cookie
1.session在何时被创建一个常见的误解是以为session在有客户端访问时就被创建,然而事实是直到某server端程序调用 HttpServletRequest.getSession(true) ...
- Feign【入门】
feign简介: feign是一种声明式,模板化的HTTP客户端,spring cloud对feign进行了增强,使其支持SpringMvc的相关注解,并整合了ribbon做负载均衡.在spring ...
- 02-19 k近邻算法(鸢尾花分类)
[TOC] 更新.更全的<机器学习>的更新网站,更有python.go.数据结构与算法.爬虫.人工智能教学等着你:https://www.cnblogs.com/nickchen121/ ...
- 【DP合集】合并 union
给出一个 1 ∼ N 的序列 A ( A 1 , A 2 , ..., A N ) .你每次可以将两个相邻的元素合并,合并后的元素权值即为 这两个元素的权值之和.求将 A 变为一个非降序列,最少需要多 ...
- CSS定位机制:浮动 float及清除浮动的常用方法
CSS的定位机制 1.普通流(标准流) 默认状态,元素自动从左往右,从上往下排列 块元素的特征: 独占一行 可以设置宽高 如果不设置宽度,宽度默认为容器的100% 常见的块元素:div p h1-h6 ...
- 终端 10X 工作法(一)
目录 1. Terminal 2. Grep 3. Sed 4. Awk 5. Xargs 6. Find 在 github 上面有一个 700 多人 star 的 repo 叫做 Bash-Onel ...
- 利用pyecharts将数据可视化
可视化展示在数据分析领域中是一个至关重要的点,好的可视化展示对我们的结果分析有更好的支持作用. 一.问题 在数据分析的时代里面我们需要将数据的可视化展现出来,更加方便用户的观察.如下图 有些时候我们需 ...