我想实现一个网状网络,这意味着每个节点都可以是客户端/服务器。我不想在这个网络中使用服务器。而且我还想广播每个节点发送的消息。我正在使用 NIO 库。这是代码,因为我使用的是 UDP 并且消息应该广播,所以我使用 null 作为接收器,但问题是当我运行代码时,它显示了这个错误“NullPointerException”,因为我使用 null 作为接收器的地址. 这是代码:
public class peer {
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(1111));
System.out.println("hello, enter your message");
Scanner scanner=new Scanner(System.in);
String msg= scanner.nextLine();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(msg.getBytes());
buf.flip();
channel.send(buf, null);
channel.receive(buf);
}