通过非阻塞 Java NIO 套接字传递对象并不总是成功

发布于 2024-11-25 09:33:05 字数 2083 浏览 2 评论 0原文

我正在编写一个程序来使用 Java NIO 非阻塞套接字模拟 P2P 网络上的对等点。这个想法是让每个对等点使用相同的代码来发送和接收消息以及允许对等点引导到网络的服务器。

我遇到的问题是,尽管最多四个对等点可以成功加入网络并相互通信(Ping、Pong、Query 和 QueryHit),但当我添加第五个对等点时,服务器总是报告“StreamCorruptedException”。我已经检查过这个网站以及Java NIO代码/教程网站以获取解决方案,但无济于事。我知道通过非阻塞套接字发送对象并不容易/理想(特别是使用 ObjectOutputStream 和 ObjectInputStream),但我想尽量减少线程的使用(而且我不想从头开始重写!)。

我将首先展示最重要的方法(消息发送和接收),但如果需要,我可以稍后添加更多方法。

写入方法:

public void write(SelectionKey selKey){ 
    SocketChannel channel = (SocketChannel)selKey.channel();
    ArrayList<Message> queue = pending.get(channel);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos;
    try{
        oos = new ObjectOutputStream(baos);
    }catch(Exception e){
        System.err.println("Could not create object output stream. Aborting...");
        return;
    }

    while(!queue.isEmpty()){            
        Message message = queue.get(0);
        buffer.clear();
        try{
            oos.writeObject(message);
            buffer = ByteBuffer.wrap(baos.toByteArray());
            channel.write(buffer);
            oos.flush();
            baos.flush();
        }catch(Exception e){
            System.err.println("Could not parse object. Aborting...");
            queue.remove(0);
            return;
        }
        queue.remove(0);
    }
    selKey.interestOps(SelectionKey.OP_READ);
}

和读取方法:

public Message read(SelectionKey selKey) throws IOException, ClassNotFoundException{
    SocketChannel channel = (SocketChannel)selKey.channel();        
    Message message = null;

    buffer = ByteBuffer.allocate(8192);

    int bytesRead = channel.read(buffer);
    if(bytesRead > 0){
        buffer.flip();
        InputStream bais = new ByteArrayInputStream(buffer.array(), 0, buffer.limit());
        ObjectInputStream ois = new ObjectInputStream(bais); //Offending line. Produces the StreamCorruptedException.
        message = (Message)ois.readObject();
        ois.close();
    }

    return message;
}

任何帮助将不胜感激!

I'm writing a program to simulate peers on a P2P network using Java NIO non-blocking sockets. The idea is to have each peer use the same code for sending and receiving messages as well as a server to allow peers to bootstrap into the network.

The problem I'm having is although up to four peers can successfully join the network and talk to each other (Ping, Pong, Query and QueryHit), when I add a fifth peer the server always reports a "StreamCorruptedException". I've checked this website as well as Java NIO code/tutorial websites for solutions, but to no avail. I understand sending objects over non-blocking sockets is not easy/ideal (especially with ObjectOutputStream and ObjectInputStream), but I want to minimise the use of threads (also I don't want to re-write this from scratch!).

I'll show the most important methods first (message send and receive), but I can add more later if required.

Write method:

public void write(SelectionKey selKey){ 
    SocketChannel channel = (SocketChannel)selKey.channel();
    ArrayList<Message> queue = pending.get(channel);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos;
    try{
        oos = new ObjectOutputStream(baos);
    }catch(Exception e){
        System.err.println("Could not create object output stream. Aborting...");
        return;
    }

    while(!queue.isEmpty()){            
        Message message = queue.get(0);
        buffer.clear();
        try{
            oos.writeObject(message);
            buffer = ByteBuffer.wrap(baos.toByteArray());
            channel.write(buffer);
            oos.flush();
            baos.flush();
        }catch(Exception e){
            System.err.println("Could not parse object. Aborting...");
            queue.remove(0);
            return;
        }
        queue.remove(0);
    }
    selKey.interestOps(SelectionKey.OP_READ);
}

And the read method:

public Message read(SelectionKey selKey) throws IOException, ClassNotFoundException{
    SocketChannel channel = (SocketChannel)selKey.channel();        
    Message message = null;

    buffer = ByteBuffer.allocate(8192);

    int bytesRead = channel.read(buffer);
    if(bytesRead > 0){
        buffer.flip();
        InputStream bais = new ByteArrayInputStream(buffer.array(), 0, buffer.limit());
        ObjectInputStream ois = new ObjectInputStream(bais); //Offending line. Produces the StreamCorruptedException.
        message = (Message)ois.readObject();
        ois.close();
    }

    return message;
}

Any help will be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一页 2024-12-02 09:33:05
int bytesRead = channel.read(buffer);
if(bytesRead > 0){
    buffer.flip();
    InputStream bais = new ByteArrayInputStream(buffer.array(), 0, buffer.limit());
    ObjectInputStream ois = new ObjectInputStream(bais); //Offending line. Produces the StreamCorruptedException.
    message = (Message)ois.readObject();
    ois.close();
}

在这里,您混合了阻塞和非阻塞 I/O。缓冲区不会从套接字中彻底读取,它只会读取可用的内容。如果您打算采用这种方法,您需要首先将所有数据读入缓冲区。

int bytesRead = channel.read(buffer);
if(bytesRead > 0){
    buffer.flip();
    InputStream bais = new ByteArrayInputStream(buffer.array(), 0, buffer.limit());
    ObjectInputStream ois = new ObjectInputStream(bais); //Offending line. Produces the StreamCorruptedException.
    message = (Message)ois.readObject();
    ois.close();
}

Here you're mixing blocking and non-blocking I/O. The buffer will not have exhaustively read from the socket, it will only have read what is available. If you're going to take this approach you need to read all of the data into the buffer first.

〆凄凉。 2024-12-02 09:33:05

您不能假设您的读取将返回一个块中的整个对象。您需要一个“带外”(好吧,在 ObjectStream 带外)协议来确保您接收完整的消息,并根据需要从读取的块中组装消息。对于非阻塞来说,这将比现在复杂得多。

You can't assume that your read will return the entire object in one chunk. You need an "out-of-band" (well, out of ObjectStream band) protocol to insure that you are receiving complete messages, assembling messages from read chunks as necessary. For non-blocking this will be a good deal more complicated than what you have now.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文