PlainDatagramSocketImpl (IOException: 不允许操作)

Mar*_*cel 5 java sockets udp network-programming

我在使用 DatagramSockets 时遇到以下问题:

java.io.IOException: Operation is not permitted.
    at java.net.PlainDatagramSocketImpl.send(Native Method)
    at java.net.DatagramSocket.send(DatagramSocket.java:693)
Run Code Online (Sandbox Code Playgroud)

异常随机发生,我真的看不到模式。这让我更难调试它。

尽管如此,我怀疑当我发送大量数据时它会更频繁地发生。

我有多个线程通过这个套接字发送,但这应该不是问题,因为我读过 Java 套接字是线程安全的。

有人能告诉我什么时候以及在什么条件下可以抛出这样的异常吗?

这是我的基本网络代码:

package de.oompf.netwrk;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

class Server implements Runnable {

    private final EventBus bus;
    private final Thread serverThread;
    private final DatagramSocket socket;

    Server(EventBus bus) throws SocketException {
    this.bus = bus;
    serverThread = new Thread(this, "Server Thread");
    socket = getBoundSocket();
    socket.setSoTimeout(2400);
    }

    private static DatagramSocket getBoundSocket() throws SocketException {
    for (int port : Configuration.getPortList()) {
        try {
            return new DatagramSocket(port);
        } catch (SocketException e) {
        }
    }
    return new DatagramSocket(0);
    }

    int getPort() {
    return socket.getLocalPort();
    }

    void start() {
    bus.subscribe(this);
    serverThread.start();
    }

    void stop() {
    serverThread.interrupt();
    socket.close();
    }

    @Override
    public void run() {
    DatagramPacket p = new DatagramPacket(new byte[4096], 4096);
    while (!serverThread.isInterrupted()) {
        try {
            socket.receive(p);
            bus.publish(new IncomingPacket(p.getData(), p.getLength(), p.getAddress(), p.getPort()));
        } catch (IOException e) {
            if (socket.isClosed()) {
                break;
            }
        }
    }
    }

    void send(OutgoingPacket p) {
    try {
        if (p.getData()[0] == 0x03) {
        }
        socket.send(new DatagramPacket(p.getData(), p.getData().length, p.getSocketAddress()));
    } catch (IOException e) {
        if (socket.isClosed()) {
            serverThread.interrupt();
        } else {
            e.printStackTrace();
        }
    }
    }
}
Run Code Online (Sandbox Code Playgroud)

有很多类在这背后工作。我只是要在我的堆栈跟踪结束的地方发布几行。

private void handleBootstrapRequest(IncomingPacket p) {
if (p.getLength() == 21) {
    byte[] requestNodeBytes = new byte[20];
    System.arraycopy(p.getData(), 1, requestNodeBytes, 0, 20);
    try {
        Node requestNode = new Node(requestNodeBytes);
        if (needsRelay(requestNode)) {
            byte[] forwardPacket = new byte[47];
            forwardPacket[0] = 0x07;
            System.arraycopy(requestNode.getBytes(), 0, forwardPacket, 1, 20);
            System.arraycopy(me.getBytes(), 0, forwardPacket, 21, 20);
            System.arraycopy(p.getAddress().getAddress(), 0, forwardPacket, 41, 4);
            System.arraycopy(ByteBuffer.allocate(2).putShort((short) (p.getPort() - Short.MAX_VALUE)).array(), 0, forwardPacket, 45, 2);
            /* Will send a packet (doing some routing first) */
            relay(forwardPacket, requestNode);
        } else {
            List<Neighbour> references = routing.getClosest(requestNode, 7);
            byte[] answerPacket = new byte[2 + references.size() * 26];
            answerPacket[0] = 0x06;
            answerPacket[1] = (byte) references.size();
            for (int i = 0; i < references.size(); i++) {
                Neighbour n = references.get(i);
                System.arraycopy(n.getBytes(), 0, answerPacket, 2 + i * 26, 20);
                System.arraycopy(n.getAddress().getAddress().getAddress(), 0, answerPacket, 22 + i * 26, 4);
                System.arraycopy(ByteBuffer.allocate(2).putShort((short) (n.getAddress().getPort() - Short.MAX_VALUE)).array(), 0, answerPacket, 26 + i * 26, 2);
            }
            /* That's where my stack trace ends and where the packet gets onto an event bus (100% working properly) */
            bus.publish(new OutgoingPacket(answerPacket, p.getSocketAddress()));
        }

        byte[] quickResponse = new byte[21];
        quickResponse[0] = 0x02;
        System.arraycopy(me.getBytes(), 0, quickResponse, 1, 20);

        /* see last comment */
        bus.publish(new OutgoingPacket(quickResponse, p.getSocketAddress()));
    } catch (InvalidNodeException e) {
    }
}
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,当我的数据包处理程序池调用多个数据包处理程序时,事件总线上可能有多个传出数据包。

Mar*_*cel 0

经过更多调查,我发现我的问题是由多个线程同时访问 DatagramSocket.send 引起的。

要解决此问题,您需要同步您的发送方法。

试试这个代码。它可能会重现java.io.IOException: 不允许操作。

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class Test {

    public static void main(String[] args) {
        new Test().now();
    }

    public void now() {
        try {
            DatagramSocket sock = new DatagramSocket(0);
            for (int i = 0; i < 32; i++) {
                new Thread(new Sender(sock)).start();
            }
        } catch (SocketException e) {
        }
    }

    public class Sender implements Runnable {

        private final DatagramSocket sock;

        public Sender(DatagramSocket sock) {
            this.sock = sock;
        }

        @Override
        public void run() {
            for(int i=0; i<12; i++) {
                try {
                    sock.send(new DatagramPacket(new byte[20], 20, new InetSocketAddress(InetAddress.getByName("example.com"), 80)));
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)