我想定期广播我目录中所有可用文件的名称。我的计划有什么问题?运行该程序会出现以下错误:
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:183)
at java.nio.ByteBuffer.put(ByteBuffer.java:832)
at UDPServer.main(UDPServer.java:42)
这是服务器代码:
public class UDPServer
{
public static void main(String[] args)throws IOException
{
try (DatagramChannel channel =
DatagramChannel.open())
{
InetSocketAddress local = new InetSocketAddress(0);
channel.socket().bind(local);
InetSocketAddress broadcast = new InetSocketAddress("255.255.255.255",5959);
ByteBuffer buffer = ByteBuffer.allocate(10000);
while(true)
{
//channel.connect(broadcast);
int n=buffer.position()/2;
//buffer.flip();
buffer.rewind();
String fileName = new String();
for(int i=0;i<n;i++)
fileName += buffer.getChar();
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(fileName));
for(Path p : stream)
{
buffer.put(p.toString().getBytes());
buffer.flip();
channel.send(buffer, broadcast);
buffer.clear();
}
}
}
}
}
更新1:
我已将第一个buffer.flip()
更改为buffer.rewind()
。这删除了BufferOverflowException
。接下来我得到了IllegalStateException: connect already invoked
。所以我删除了channel.connect(broadcast)
。最后,由file.FileSystemException
引起IOException: Too many open files
。我不知道从哪里开始。