Search in sources :

Example 81 with DatagramPacket

use of java.net.DatagramPacket in project physical-web by google.

the class Ssdp method run.

@Override
public void run() {
    Thread currentThread = Thread.currentThread();
    byte[] buf = new byte[1024];
    Log.d(TAG, "SSDP scan started");
    while (!currentThread.isInterrupted() && mDatagramSocket != null) {
        try {
            DatagramPacket dp = new DatagramPacket(buf, buf.length);
            mDatagramSocket.receive(dp);
            String txt = new String(dp.getData(), StandardCharsets.UTF_8);
            SsdpMessage msg = new SsdpMessage(txt);
            mSsdpCallback.onSsdpMessageReceived(msg);
        } catch (SocketTimeoutException e) {
            Log.d(TAG, e.getMessage());
            break;
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }
    // cleanup if needed
    synchronized (this) {
        if (mThread == currentThread) {
            mThread = null;
            if (mDatagramSocket != null) {
                mDatagramSocket.close();
                mDatagramSocket = null;
            }
        }
    }
    Log.d(TAG, "SSDP scan terminated");
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException)

Example 82 with DatagramPacket

use of java.net.DatagramPacket in project j2objc by google.

the class DatagramChannelImpl method receiveImpl.

private SocketAddress receiveImpl(ByteBuffer target, boolean loop) throws IOException {
    SocketAddress retAddr = null;
    DatagramPacket receivePacket;
    int oldposition = target.position();
    int received;
    // TODO: disallow mapped buffers and lose this conditional?
    if (target.hasArray()) {
        receivePacket = new DatagramPacket(target.array(), target.position() + target.arrayOffset(), target.remaining());
    } else {
        receivePacket = new DatagramPacket(new byte[target.remaining()], target.remaining());
    }
    do {
        received = NetworkBridge.recvfrom(false, fd, receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength(), 0, receivePacket, isConnected());
        if (receivePacket.getAddress() != null) {
            if (received > 0) {
                if (target.hasArray()) {
                    target.position(oldposition + received);
                } else {
                    // copy the data of received packet
                    target.put(receivePacket.getData(), 0, received);
                }
            }
            retAddr = receivePacket.getSocketAddress();
            break;
        }
    } while (loop);
    return retAddr;
}
Also used : DatagramPacket(java.net.DatagramPacket) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 83 with DatagramPacket

use of java.net.DatagramPacket in project gradle by gradle.

the class FileLockCommunicator method receive.

public long receive() throws GracefullyStoppedException {
    try {
        byte[] bytes = new byte[9];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        socket.receive(packet);
        return decode(bytes);
    } catch (IOException e) {
        if (!stopped) {
            throw new RuntimeException(e);
        }
        throw new GracefullyStoppedException();
    }
}
Also used : DatagramPacket(java.net.DatagramPacket)

Example 84 with DatagramPacket

use of java.net.DatagramPacket in project XobotOS by xamarin.

the class UDPMessageChannel method processIncomingDataPacket.

/**
     * Process an incoming datagram
     *
     * @param packet
     *            is the incoming datagram packet.
     */
private void processIncomingDataPacket(DatagramPacket packet) throws Exception {
    this.peerAddress = packet.getAddress();
    int packetLength = packet.getLength();
    // Read bytes and put it in a eueue.
    byte[] bytes = packet.getData();
    byte[] msgBytes = new byte[packetLength];
    System.arraycopy(bytes, 0, msgBytes, 0, packetLength);
    // Do debug logging.
    if (sipStack.isLoggingEnabled()) {
        this.sipStack.getStackLogger().logDebug("UDPMessageChannel: processIncomingDataPacket : peerAddress = " + peerAddress.getHostAddress() + "/" + packet.getPort() + " Length = " + packetLength);
    }
    SIPMessage sipMessage = null;
    try {
        this.receptionTime = System.currentTimeMillis();
        sipMessage = myParser.parseSIPMessage(msgBytes);
        myParser = null;
    } catch (ParseException ex) {
        // let go of the parser reference.
        myParser = null;
        if (sipStack.isLoggingEnabled()) {
            this.sipStack.getStackLogger().logDebug("Rejecting message !  " + new String(msgBytes));
            this.sipStack.getStackLogger().logDebug("error message " + ex.getMessage());
            this.sipStack.getStackLogger().logException(ex);
        }
        // JvB: send a 400 response for requests (except ACK)
        // Currently only UDP, @todo also other transports
        String msgString = new String(msgBytes, 0, packetLength);
        if (!msgString.startsWith("SIP/") && !msgString.startsWith("ACK ")) {
            String badReqRes = createBadReqRes(msgString, ex);
            if (badReqRes != null) {
                if (sipStack.isLoggingEnabled()) {
                    sipStack.getStackLogger().logDebug("Sending automatic 400 Bad Request:");
                    sipStack.getStackLogger().logDebug(badReqRes);
                }
                try {
                    this.sendMessage(badReqRes.getBytes(), peerAddress, packet.getPort(), "UDP", false);
                } catch (IOException e) {
                    this.sipStack.getStackLogger().logException(e);
                }
            } else {
                if (sipStack.isLoggingEnabled()) {
                    sipStack.getStackLogger().logDebug("Could not formulate automatic 400 Bad Request");
                }
            }
        }
        return;
    }
    if (sipMessage == null) {
        if (sipStack.isLoggingEnabled()) {
            this.sipStack.getStackLogger().logDebug("Rejecting message !  + Null message parsed.");
        }
        if (pingBackRecord.get(packet.getAddress().getHostAddress() + ":" + packet.getPort()) == null) {
            byte[] retval = "\r\n\r\n".getBytes();
            DatagramPacket keepalive = new DatagramPacket(retval, 0, retval.length, packet.getAddress(), packet.getPort());
            ((UDPMessageProcessor) this.messageProcessor).sock.send(keepalive);
            this.sipStack.getTimer().schedule(new PingBackTimerTask(packet.getAddress().getHostAddress(), packet.getPort()), 1000);
        }
        return;
    }
    ViaList viaList = sipMessage.getViaHeaders();
    // Check for the required headers.
    if (sipMessage.getFrom() == null || sipMessage.getTo() == null || sipMessage.getCallId() == null || sipMessage.getCSeq() == null || sipMessage.getViaHeaders() == null) {
        String badmsg = new String(msgBytes);
        if (sipStack.isLoggingEnabled()) {
            this.sipStack.getStackLogger().logError("bad message " + badmsg);
            this.sipStack.getStackLogger().logError(">>> Dropped Bad Msg " + "From = " + sipMessage.getFrom() + "To = " + sipMessage.getTo() + "CallId = " + sipMessage.getCallId() + "CSeq = " + sipMessage.getCSeq() + "Via = " + sipMessage.getViaHeaders());
        }
        return;
    }
    // For response, just get the port from the packet.
    if (sipMessage instanceof SIPRequest) {
        Via v = (Via) viaList.getFirst();
        Hop hop = sipStack.addressResolver.resolveAddress(v.getHop());
        this.peerPort = hop.getPort();
        this.peerProtocol = v.getTransport();
        this.peerPacketSourceAddress = packet.getAddress();
        this.peerPacketSourcePort = packet.getPort();
        try {
            this.peerAddress = packet.getAddress();
            // Check to see if the received parameter matches
            // the peer address and tag it appropriately.
            boolean hasRPort = v.hasParameter(Via.RPORT);
            if (hasRPort || !hop.getHost().equals(this.peerAddress.getHostAddress())) {
                v.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress());
            }
            if (hasRPort) {
                v.setParameter(Via.RPORT, Integer.toString(this.peerPacketSourcePort));
            }
        } catch (java.text.ParseException ex1) {
            InternalErrorHandler.handleException(ex1);
        }
    } else {
        this.peerPacketSourceAddress = packet.getAddress();
        this.peerPacketSourcePort = packet.getPort();
        this.peerAddress = packet.getAddress();
        this.peerPort = packet.getPort();
        this.peerProtocol = ((Via) viaList.getFirst()).getTransport();
    }
    this.processMessage(sipMessage);
}
Also used : Hop(javax.sip.address.Hop) IOException(java.io.IOException) SIPRequest(gov.nist.javax.sip.message.SIPRequest) Via(gov.nist.javax.sip.header.Via) ViaList(gov.nist.javax.sip.header.ViaList) DatagramPacket(java.net.DatagramPacket) SIPMessage(gov.nist.javax.sip.message.SIPMessage) ParseException(java.text.ParseException) ParseException(java.text.ParseException)

Example 85 with DatagramPacket

use of java.net.DatagramPacket in project XobotOS by xamarin.

the class DatagramChannelImpl method receiveImpl.

private SocketAddress receiveImpl(ByteBuffer target, boolean loop) throws IOException {
    SocketAddress retAddr = null;
    DatagramPacket receivePacket;
    int oldposition = target.position();
    int received = 0;
    // TODO: disallow mapped buffers and lose this conditional?
    if (target.hasArray()) {
        receivePacket = new DatagramPacket(target.array(), target.position() + target.arrayOffset(), target.remaining());
    } else {
        receivePacket = new DatagramPacket(new byte[target.remaining()], target.remaining());
    }
    do {
        received = IoBridge.recvfrom(false, fd, receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength(), 0, receivePacket, isConnected());
        if (receivePacket != null && receivePacket.getAddress() != null) {
            if (received > 0) {
                if (target.hasArray()) {
                    target.position(oldposition + received);
                } else {
                    // copy the data of received packet
                    target.put(receivePacket.getData(), 0, received);
                }
            }
            retAddr = receivePacket.getSocketAddress();
            break;
        }
    } while (loop);
    return retAddr;
}
Also used : DatagramPacket(java.net.DatagramPacket) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

DatagramPacket (java.net.DatagramPacket)302 IOException (java.io.IOException)126 DatagramSocket (java.net.DatagramSocket)121 InetAddress (java.net.InetAddress)69 SocketException (java.net.SocketException)43 Test (org.junit.Test)35 InetSocketAddress (java.net.InetSocketAddress)34 SocketTimeoutException (java.net.SocketTimeoutException)30 UnknownHostException (java.net.UnknownHostException)21 MulticastSocket (java.net.MulticastSocket)18 InterruptedIOException (java.io.InterruptedIOException)17 SocketAddress (java.net.SocketAddress)15 ByteBuffer (java.nio.ByteBuffer)11 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 SyslogConnection (org.opennms.netmgt.syslogd.api.SyslogConnection)11 PortUnreachableException (java.net.PortUnreachableException)9 ArrayList (java.util.ArrayList)9 SyslogMessageLogDTO (org.opennms.netmgt.syslogd.api.SyslogMessageLogDTO)8 BindException (java.net.BindException)7 Transactional (org.springframework.transaction.annotation.Transactional)7