Java Code Examples for java.net.DatagramPacket

The following are top voted examples for showing how to use java.net.DatagramPacket. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: T0rlib4Android   File: Socks5DatagramSocket.java   View source code 7 votes vote down vote up
/**
 * Sends the Datagram either through the proxy or directly depending on
 * current proxy settings and destination address. <BR>
 * 
 * <B> NOTE: </B> DatagramPacket size should be at least 10 bytes less than
 * the systems limit.
 * 
 * <P>
 * See documentation on java.net.DatagramSocket for full details on how to
 * use this method.
 * 
 * @param dp
 *            Datagram to send.
 * @throws IOException
 *             If error happens with I/O.
 */
public void send(DatagramPacket dp) throws IOException {
	// If the host should be accessed directly, send it as is.
	if (!server_mode && proxy.isDirect(dp.getAddress())) {
		super.send(dp);
		log.debug("Sending datagram packet directly:");
		return;
	}

	final byte[] head = formHeader(dp.getAddress(), dp.getPort());
	byte[] buf = new byte[head.length + dp.getLength()];
	final byte[] data = dp.getData();

	// Merge head and data
	System.arraycopy(head, 0, buf, 0, head.length);
	// System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
	System.arraycopy(data, 0, buf, head.length, dp.getLength());

	if (encapsulation != null) {
		buf = encapsulation.udpEncapsulate(buf, true);
	}

	super.send(new DatagramPacket(buf, buf.length, relayIP, relayPort));
}
 
Example 2
Project: litiengine   File: UdpPacketReceiver.java   View source code 6 votes vote down vote up
@Override
public void run() {
  while (!this.isTerminated) {
    final byte[] data = new byte[10000];
    final DatagramPacket packet = new DatagramPacket(data, data.length);
    try {
      this.socket.receive(packet);
    } catch (final IOException e) {
      log.log(Level.SEVERE, e.getMessage(), e);
    }

    for (final IIncomingPacketObserver packetObserver : this.incomingPacketObservers) {
      packetObserver.packetReceived(packet.getData(), packet.getAddress(), packet.getPort());
    }
  }

  this.socket.close();
}
 
Example 3
Project: java-coap   File: MulticastSocketTransport.java   View source code 6 votes vote down vote up
private void readingLoop(CoapReceiver coapReceiver) {
    byte[] readBuffer = new byte[2048];

    try {
        while (true) {
            DatagramPacket datagramPacket = new DatagramPacket(readBuffer, readBuffer.length);
            mcastSocket.receive(datagramPacket);
            InetSocketAddress adr = (InetSocketAddress) datagramPacket.getSocketAddress();
            if (LOGGER.isDebugEnabled() && adr.getAddress().isMulticastAddress()) {
                LOGGER.debug("Received multicast message from: " + datagramPacket.getSocketAddress());
            }

            try {
                final CoapPacket coapPacket = CoapPacket.read(adr, datagramPacket.getData(), datagramPacket.getLength());
                receivedMessageWorker.execute(() -> coapReceiver.handle(coapPacket, TransportContext.NULL));
            } catch (CoapException e) {
                LOGGER.warn(e.getMessage());
            }
        }
    } catch (IOException ex) {
        if (!ex.getMessage().startsWith("Socket closed")) {
            LOGGER.warn(ex.getMessage(), ex);
        }
    }
}
 
Example 4
Project: WifiChatSharing   File: MessageActivity.java   View source code 6 votes vote down vote up
@Override
protected Boolean doInBackground(Void... voids) {

    Thread newThread = new Thread() {

        public void run() {
            while (true) {
                byte[] recvPkt = new byte[1024];
                DatagramPacket recv = new DatagramPacket(recvPkt, recvPkt.length);
                try {
                    socket.receive(recv);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                final String medd = new String(recvPkt, 0, recv.getLength());
                recQue.add(medd);
                updateListView(medd);
            }
        }
    };
    newThread.start();
    return null;
}
 
Example 5
Project: ServerBrowser   File: SampQuery.java   View source code 6 votes vote down vote up
private DatagramPacket assemblePacket(final char type) {
	final StringTokenizer tok = new StringTokenizer(server.getHostAddress(), ".");
	final StringBuffer packetData = new StringBuffer("SAMP");
	
	while (tok.hasMoreTokens()) {// The splitted parts of the ip will be parsed into ints and casted into characters
		packetData.append((char) Integer.parseInt(tok.nextToken()));
	}
	
	/*
	 * At this point the buffer contains something like 'SAMPx!2.' where each character after
	 * 'SAMP' is a part of the ip address
	 */
	
	packetData.append((char) (serverPort & 0xFF)).append((char) (serverPort >> 8 & 0xFF)).append(type);
	
	if (type == PACKET_MIRROR_CHARACTERS) {// Apply 4 random bytes, in case it was a mirror query
											// final Random random = ThreadLocalRandom.current();
											// final byte[] toMirror = new byte[4];
											// random.nextBytes(toMirror);
		packetData.append("0101"); // TODO(MSC) Fix temporarily
	}
	
	final byte[] data = packetData.toString().getBytes(StandardCharsets.US_ASCII);
	return new DatagramPacket(data, data.length, server, serverPort);
}
 
Example 6
Project: sonos-remote-things   File: Device.java   View source code 6 votes vote down vote up
/**
 * Instantiate a new Device Object from a SSDP discovery response packet.
 * @param ssdpResult SSDP Discovery Response packet.
 * @return Device
 */
public static Device parse(DatagramPacket ssdpResult) {
    HashMap<String, String> headers = new HashMap<String, String>();
    Pattern pattern = Pattern.compile("(.*): (.*)");

    String[] lines = new String(ssdpResult.getData()).split("\r\n");

    for (String line : lines) {
        Matcher matcher = pattern.matcher(line);
        if(matcher.matches()) {
            headers.put(matcher.group(1).toUpperCase(), matcher.group(2));
        }
    }

    return new Device(
            ssdpResult.getAddress().getHostAddress(),
            headers.get("LOCATION"),
            headers.get("SERVER"),
            headers.get("ST"),
            headers.get("USN"));
}
 
Example 7
Project: 2017SteamBot2   File: UDPReceive.java   View source code 6 votes vote down vote up
public UDPReceive() {
	
	try {
		int port = 10030;

		// Create a socket to listen on the port.
		dsocket = new DatagramSocket(port);
		dsocket.setSoTimeout(2);
		
		// Create a buffer to read datagrams into.
		buffer = new byte[2048];

		// Create a packet to receive data into the buffer
		packet = new DatagramPacket(buffer, buffer.length);
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example 8
Project: broadlink-java-api   File: RM2Device.java   View source code 6 votes vote down vote up
/**
 * Requests the RM2 to return the room temperature<br>
 * <br>
 * The {@link #auth() auth()} method must be ran before these commands
 * 
 * @return The room temperature in a floating number
 * @throws IOException
 *             Problems on sending packet
 */
public double getTemp() throws Exception {
    DatagramPacket packet = sendCmdPkt(new RMTempCmdPayload());
    byte[] data = packet.getData();

    int err = data[0x22] | (data[0x23] << 8);

    if (err == 0) {
        AES aes = new AES(getIv(), getKey());

        byte[] encData = BLDevice.subbytes(data, 0x38, data.length);

        encData = chgLen(encData, 1024);

        byte[] pl = aes.decrypt(encData);

        return (double) (pl[0x4] * 10 + pl[0x5]) / 10.0;
    } else {
        System.out.println(Integer.toHexString(err) + " / " + err);
    }

    return -1;
}
 
Example 9
Project: jda-async-packetprovider   File: AsyncPacketProvider.java   View source code 6 votes vote down vote up
@Override
public void run() {
	try {
		do {
			DatagramPacket packet = AsyncPacketProvider.this.packetProvider.getNextPacket(this.changeTalking);
			if (packet == null) {
				 //actual value doesn't matter, as long as the thread gets taken out of scheduling
				Thread.sleep(40);
			} else if(!this.queue.offer(packet, 1, SECONDS) && !this.stopRequested) {
				AsyncPacketProvider.log.debug("Clock leap or something? Trying again.");
				if (!this.queue.offer(packet, 5, SECONDS) && !this.stopRequested) {
					AsyncPacketProvider.log.warn("Missed a packet, queue is not being drained. Audio send system shutdown?");
				}
			}
		} while (!this.stopRequested);
	} catch (InterruptedException ex) {
		Thread.currentThread().interrupt();
	}
}
 
Example 10
Project: OpenJSharp   File: SnmpAdaptorServer.java   View source code 6 votes vote down vote up
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
Example 11
Project: RISE-V2G   File: UDPServer.java   View source code 6 votes vote down vote up
public boolean send(V2GTPMessage message, Inet6Address udpClientAddress, int udpClientPort) {
	 byte[] v2gTPMessage = message.getMessage();
	// Set up the UDP packet containing the V2GTP message to be sent to the UDP client
	DatagramPacket udpServerPacket = new DatagramPacket(v2gTPMessage, 
														v2gTPMessage.length,
														udpClientAddress,
														udpClientPort);
	
	// Send the response to the UDP client
	try {
		udpServerSocket.send(udpServerPacket);
		getLogger().debug("Message sent");
		
		return true;
	} catch (IOException e) {
		getLogger().error("UDP response failed (IOException) while trying to send message!", e);
		return false;
	}
}
 
Example 12
Project: cordova-plugin-smartconfig   File: UDPSocketServer.java   View source code 6 votes vote down vote up
/**
 * Constructor of UDP Socket Server
 * 
 * @param port
 *            the Socket Server port
 * @param socketTimeout
 *            the socket read timeout
 * @param context
 *            the context of the Application
 */
public UDPSocketServer(int port, int socketTimeout, Context context) {
	this.mContext = context;
	this.buffer = new byte[64];
	this.mReceivePacket = new DatagramPacket(buffer, 64);
	try {
		this.mServerSocket = new DatagramSocket(port);
		this.mServerSocket.setSoTimeout(socketTimeout);
		this.mIsClosed = false;
		WifiManager manager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		mLock = manager.createMulticastLock("test wifi");
		Log.d(TAG, "mServerSocket is created, socket read timeout: "
				+ socketTimeout + ", port: " + port);
	} catch (IOException e) {
		Log.e(TAG, "IOException");
		e.printStackTrace();
	}
}
 
Example 13
Project: openjdk-jdk10   File: RespondToRetransmit.java   View source code 6 votes vote down vote up
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (needPacketDuplicate && (!(isClient ^ engine.getUseClientMode()))) {
        DatagramPacket packet = getPacket(packets, handshakeType);
        if (packet != null) {
            needPacketDuplicate = false;

            System.out.println("Duplicate the flight.");
            List<DatagramPacket> duplicates = new ArrayList<>();
            finished = super.produceHandshakePackets(
                    engine, socketAddr, side, duplicates);
            packets.addAll(duplicates);
        }
    }

    return finished;
}
 
Example 14
Project: OpenJSharp   File: SnmpRequestHandler.java   View source code 6 votes vote down vote up
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
 
Example 15
Project: ZooKeeper   File: LENonTerminateTest.java   View source code 6 votes vote down vote up
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);
        
        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
 
Example 16
Project: NSS   File: DataMessage.java   View source code 6 votes vote down vote up
public void create(int timeId){
	this.timeId=timeId;
	dpData=new byte[this.length+16+8];
	ByteShortConvert.toByteArray(ver, dpData, 0);  //add: ver
	ByteShortConvert.toByteArray(sType, dpData, 2);  //add: service type
	
	ByteIntConvert.toByteArray(connectId, dpData, 4); //add: sequence
	ByteIntConvert.toByteArray(clientId, dpData, 8); //add: sequence
	
	ByteIntConvert.toByteArray(this.sequence, dpData, 12); //add: sequence
	ByteShortConvert.toByteArray((short) this.length, dpData, 16); //add:length
	ByteIntConvert.toByteArray(this.timeId, dpData, 18); //add: sequence
	System.arraycopy(this.data, 0, dpData, 22, this.length);
	dp=new DatagramPacket(dpData,dpData.length);
	dp.setAddress(dstAddress);
	dp.setPort(dstPort);
	
}
 
Example 17
Project: JDA-Audio   File: AudioPacket.java   View source code 6 votes vote down vote up
public static AudioPacket decryptAudioPacket(DatagramPacket packet, byte[] secretKey)
{
    TweetNaclFast.SecretBox boxer = new TweetNaclFast.SecretBox(secretKey);
    AudioPacket encryptedPacket = new AudioPacket(packet);

    byte[] extendedNonce = new byte[XSALSA20_NONCE_LENGTH];
    System.arraycopy(encryptedPacket.getNonce(), 0, extendedNonce, 0, RTP_HEADER_BYTE_LENGTH);

    byte[] decryptedAudio = boxer.open(encryptedPacket.getEncodedAudio(), extendedNonce);
    byte[] decryptedRawPacket = new byte[RTP_HEADER_BYTE_LENGTH + decryptedAudio.length];

    System.arraycopy(encryptedPacket.getNonce(), 0, decryptedRawPacket, 0, RTP_HEADER_BYTE_LENGTH);
    System.arraycopy(decryptedAudio, 0, decryptedRawPacket, RTP_HEADER_BYTE_LENGTH, decryptedAudio.length);

    return new AudioPacket(decryptedRawPacket);
}
 
Example 18
Project: openhab2-addon-hs110   File: HS110DiscoveryService.java   View source code 6 votes vote down vote up
private void detectThing(DatagramPacket packet) throws IOException {
    String data = Util
            .decrypt(new ByteArrayInputStream(Arrays.copyOfRange(packet.getData(), 0, packet.getLength())), true);

    logger.debug("Detecting HS110 by data: {}", data);

    String inetAddress = packet.getAddress().getHostAddress();
    String id = HS110.parseDeviceId(data);
    logger.debug("HS110 with id {} found on {} ", id, inetAddress);
    ThingUID thingUID = new ThingUID(HS110BindingConstants.THING_TYPE_HS110, id);
    String label = "HS110 at " + inetAddress;
    Map<String, Object> properties = new TreeMap<>();
    properties.put(HS110BindingConstants.CONFIG_IP, inetAddress);
    DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withLabel(label)
            .withProperties(properties).build();
    thingDiscovered(discoveryResult);
}
 
Example 19
Project: multicast   File: TiandeMulticastSocket.java   View source code 6 votes vote down vote up
/**
 * 组播发送消息
 * @param msg
 */
public void send(TiandeMulticastMessage msg){
	if(cast == null){
		throw new TiandeMultiCastException("Multi cast server is closed!");
	}
	
	/* 判断msg大小 */
	String msgJson = msg.toString();
	//base64转码
	String msgBase64 = Base64.encode(msgJson);
	
	/* 拆包发送 */
	TiandeMulticastMessageManager castMessageManager = new TiandeMulticastMessageManager(msgBase64, this);
	List<DatagramPacket> packetList = castMessageManager.getDatagramPacketList();
	for(int i = 0; i < packetList.size(); i++){
		try {
			/* 休眠时间 */
			Thread.sleep(intervalSend);
			
			cast.send(packetList.get(i));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 20
Project: jdk8u-jdk   File: SnmpAdaptorServer.java   View source code 6 votes vote down vote up
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
Example 21
Project: myster   File: ImmutableDatagramPacket.java   View source code 6 votes vote down vote up
public ImmutableDatagramPacket(DatagramPacket p) {
    address = p.getAddress();
    port = p.getPort();
    byte[] temp_data = p.getData();
    int length = p.getLength();

    byte[] b_temp = new byte[length];

    if (length < temp_data.length) {
        b_temp = new byte[length];

        for (int i = 0; i < length; i++) {
            b_temp[i] = temp_data[i];
        }
    } else if (length > temp_data.length) { //should not happen.
        throw new RuntimeException(
                "Length is bigger then  message, packet is garbage.");
    }

    data = b_temp;
}
 
Example 22
Project: OCast-Java   File: SSDPDiscoveryTest.java   View source code 6 votes vote down vote up
@Test
public void scanSingleResult() throws Exception {
    final DatagramSocket socketMessage = mock(DatagramSocket.class);
    doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(any(DatagramPacket.class));

    FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
    SSDPDiscovery ssdp = new SSDPDiscovery("urn:cast-ocast-org:service:cast:1", 3000) {
        @Override
        protected DatagramSocket createSocket() {
            return socketMessage;
        }
    };
    ssdp.addListener(callback);
    ssdp.start();
    callback.await(3, TimeUnit.SECONDS);
    verify(callback, times(1)).onLocationSent();
    verify(callback, times(1)).onLocationReceived(any(SSDPMessage.class));
    SSDPMessage result = callback.getResult();
    assertThat(result.getUuid(), is(equalTo("c4323fee-db4b-4227-9039-fa4b71589e26")));
}
 
Example 23
Project: messenger   File: PeerTransmission.java   View source code 6 votes vote down vote up
public void sendPacket(InetAddress address, int port, byte[] payload, int offset, int length) {
    if (address == null)
        return;
    if (Looper.myLooper() == Looper.getMainLooper()) {
        new Thread(() -> sendPacket(address, port, payload, offset, length));
        return;
    }
    DatagramPacket packet = new DatagramPacket(payload, length);
    packet.setAddress(address);
    packet.setPort(port);
    try {
        socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 24
Project: T0rlib4j   File: Socks5DatagramSocket.java   View source code 6 votes vote down vote up
/**
 * This method allows to send datagram packets with address type DOMAINNAME.
 * SOCKS5 allows to specify host as names rather than ip addresses.Using
 * this method one can send udp datagrams through the proxy, without having
 * to know the ip address of the destination host.
 * <p>
 * If proxy specified for that socket has an option resolveAddrLocally set
 * to true host will be resolved, and the datagram will be send with address
 * type IPV4, if resolve fails, UnknownHostException is thrown.
 * 
 * @param dp
 *            Datagram to send, it should contain valid port and data
 * @param host
 *            Host name to which datagram should be send.
 * @throws IOException
 *             If error happens with I/O, or the host can't be resolved when
 *             proxy settings say that hosts should be resolved locally.
 * @see Socks5Proxy#resolveAddrLocally(boolean)
 */
public void send(DatagramPacket dp, String host) throws IOException {
	if (proxy.isDirect(host)) {
		dp.setAddress(InetAddress.getByName(host));
		super.send(dp);
		return;
	}

	if ((proxy).resolveAddrLocally) {
		dp.setAddress(InetAddress.getByName(host));
	}

	final byte[] head = formHeader(host, dp.getPort());
	byte[] buf = new byte[head.length + dp.getLength()];
	final byte[] data = dp.getData();
	// Merge head and data
	System.arraycopy(head, 0, buf, 0, head.length);
	// System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
	System.arraycopy(data, 0, buf, head.length, dp.getLength());

	if (encapsulation != null) {
		buf = encapsulation.udpEncapsulate(buf, true);
	}

	super.send(new DatagramPacket(buf, buf.length, relayIP, relayPort));
}
 
Example 25
Project: maxcube-java   File: MinaDiscoveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGoodCaseDiscovery() throws Exception {
    int port = randomIntBetween(60000, 65000);
    String data = randomAsciiOfLength(18);
    try (MinaDiscoveryClient client = new MinaDiscoveryClient(port)) {
        List<DiscoveredCube> cubes = new ArrayList<>();
        NetworkInterface localhostInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
        client.startServer(localhostInterface, cubes);

        try (DatagramSocket clientSocket = new DatagramSocket()) {
            clientSocket.setReuseAddress(true);
            byte[] discoverBytes = data.getBytes(UTF_8);
            DatagramPacket sendPacket = new DatagramPacket(discoverBytes, discoverBytes.length, InetAddress.getLocalHost(), port);
            logger.info("Sending UDP packet to [{}:{}]", InetAddress.getLocalHost(), port);
            clientSocket.send(sendPacket);
        }

        // waiting without sleeping would be better
        Thread.sleep(500);

        assertThat(cubes, hasSize(greaterThan(0)));
        assertThat(cubes.stream().filter(cube -> cube.id.equals(data.substring(8, 18))).count(), is(1L));
    }
}
 
Example 26
Project: rtmp-rtsp-stream-client-java   File: RtpSocketUdp.java   View source code 6 votes vote down vote up
/**
 * This RTP socket implements a buffering mechanism relying on a FIFO of buffers and a Thread.
 */
public RtpSocketUdp(ConnectCheckerRtsp connectCheckerRtsp) {
  super();
  this.connectCheckerRtsp = connectCheckerRtsp;
  senderReportUdp = new SenderReportUdp(connectCheckerRtsp);
  senderReportUdp.reset();
  packets = new DatagramPacket[bufferCount];
  for (int i = 0; i < bufferCount; i++) {
    packets[i] = new DatagramPacket(buffers[i], 1);
  }
  try {
    mSocket = new MulticastSocket();
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 27
Project: Reer   File: FileLockCommunicator.java   View source code 5 votes vote down vote up
public void pingOwner(int ownerPort, long lockId, String displayName) {
    try {
        byte[] bytesToSend = encode(lockId);
        // Ping the owner via all available local addresses
        for (InetAddress address : addressFactory.getCommunicationAddresses()) {
            socket.send(new DatagramPacket(bytesToSend, bytesToSend.length, address, ownerPort));
        }
    } catch (IOException e) {
        throw new RuntimeException(String.format("Failed to ping owner of lock for %s (lock id: %s, port: %s)", displayName, lockId, ownerPort), e);
    }
}
 
Example 28
Project: Reer   File: FileLockCommunicator.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 29
Project: streaminglib   File: RtpStream.java   View source code 5 votes vote down vote up
@Override
public void run() {
    while (!Thread.interrupted()) {
        try {
            byte[] buffer = new byte[MTU];
            DatagramPacket p = new DatagramPacket(buffer, MTU);
            rtpSocket.receive(p);
            p.getLength();

            streamEventBus.post(new RtspSessionEvent.RtpPacketReceived(buffer));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 30
Project: openvisualtraceroute   File: UDP.java   View source code 5 votes vote down vote up
private static void test() throws Exception {
	final String hostname = "google.com";
	final String localhost = "localhost";
	final MulticastSocket datagramSocket = new MulticastSocket();
	datagramSocket.setSoTimeout(10000);
	short ttl = 1;
	final InetAddress receiverAddress = InetAddress.getByName(hostname);
	while (ttl < 100) {
		try {
			byte[] buffer = "0123456789".getBytes();
			datagramSocket.setTimeToLive(ttl++);
			final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);

			datagramSocket.send(sendPacket);

			buffer = new byte[10];
			final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);

			datagramSocket.receive(receivePacket);
			System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
					+ new String(receivePacket.getData()));
			Thread.sleep(1000);
		} catch (final SocketTimeoutException e) {
			System.out.println("timeout ttl=" + ttl);
		}
	}
}
 
Example 31
Project: NSS   File: CloseMessage_Conn.java   View source code 5 votes vote down vote up
public CloseMessage_Conn(int connectId,int clientId){
	byte[] dpData=new byte[12];
	this.clientId=clientId;
	this.connectId=connectId;
	ByteShortConvert.toByteArray(ver, dpData, 0);
	ByteShortConvert.toByteArray(sType, dpData, 2);
	ByteIntConvert.toByteArray(connectId, dpData, 4);
	ByteIntConvert.toByteArray(clientId, dpData, 8);
	dp=new DatagramPacket(dpData,dpData.length);
}
 
Example 32
Project: DecompiledMinecraft   File: LanServerDetector.java   View source code 5 votes vote down vote up
public void run()
{
    byte[] abyte = new byte[1024];

    while (!this.isInterrupted())
    {
        DatagramPacket datagrampacket = new DatagramPacket(abyte, abyte.length);

        try
        {
            this.socket.receive(datagrampacket);
        }
        catch (SocketTimeoutException var5)
        {
            continue;
        }
        catch (IOException ioexception)
        {
            LanServerDetector.logger.error((String)"Couldn\'t ping server", (Throwable)ioexception);
            break;
        }

        String s = new String(datagrampacket.getData(), datagrampacket.getOffset(), datagrampacket.getLength());
        LanServerDetector.logger.debug(datagrampacket.getAddress() + ": " + s);
        this.localServerList.func_77551_a(s, datagrampacket.getAddress());
    }

    try
    {
        this.socket.leaveGroup(this.broadcastAddress);
    }
    catch (IOException var4)
    {
        ;
    }

    this.socket.close();
}
 
Example 33
Project: ipack   File: UDPTransport.java   View source code 5 votes vote down vote up
public int receive(byte[] buf, int off, int len, int waitMillis)
    throws IOException
{
    socket.setSoTimeout(waitMillis);
    DatagramPacket packet = new DatagramPacket(buf, off, len);
    socket.receive(packet);
    return packet.getLength();
}
 
Example 34
Project: DreamSocket   File: UDPServer.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DatagramSocket socket = new DatagramSocket(6969);
    DatagramPacket packet = new DatagramPacket(new byte[500], 500);
    while (true){
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.send(packet);
    }
}
 
Example 35
Project: sonos-remote-things   File: SSDPClient.java   View source code 5 votes vote down vote up
/**
 * Discover any UPNP device using SSDP (Simple Service Discovery Protocol).
 * @param timeout in milliseconds
 * @param serviceType if null it use "ssdp:all"
 * @return List of devices discovered
 * @throws IOException
 * @see <a href="https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol">SSDP Wikipedia Page</a>
 */
public static List<Device> discover(int timeout, String serviceType) throws IOException {
    ArrayList<Device> devices = new ArrayList<Device>();
    byte[] sendData;
    byte[] receiveData = new byte[1024];

    /* Create the search request */
    StringBuilder msearch = new StringBuilder(
            "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
    if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
    else { msearch.append("ST: ").append(serviceType).append("\n"); }

    /* Send the request */
    sendData = msearch.toString().getBytes();
    DatagramPacket sendPacket = new DatagramPacket(
            sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
    DatagramSocket clientSocket = new DatagramSocket();
    clientSocket.setSoTimeout(timeout);
    clientSocket.send(sendPacket);

    /* Receive all responses */
    while (true) {
        try {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);
            devices.add(Device.parse(receivePacket));
        }
        catch (SocketTimeoutException e) { break; }
    }

    clientSocket.close();
    return Collections.unmodifiableList(devices);
}
 
Example 36
Project: sonos-remote-things   File: SSDPClient.java   View source code 5 votes vote down vote up
public static Device discoverOne(int timeout, String serviceType) throws IOException {
    Device device = null;
    byte[] sendData;
    byte[] receiveData = new byte[1024];

    /* Create the search request */
    StringBuilder msearch = new StringBuilder(
            "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
    if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
    else { msearch.append("ST: ").append(serviceType).append("\n"); }

    /* Send the request */
    sendData = msearch.toString().getBytes();
    DatagramPacket sendPacket = new DatagramPacket(
            sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
    DatagramSocket clientSocket = new DatagramSocket();
    clientSocket.setSoTimeout(timeout);
    clientSocket.send(sendPacket);

    /* Receive one response */
    try {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        device = Device.parse(receivePacket);
    }
    catch (SocketTimeoutException e) { }

    clientSocket.close();
    return device;
}
 
Example 37
Project: Transmission   File: MessageReceiver.java   View source code 5 votes vote down vote up
private void receiveMessage() throws IOException {
    byte[] data = new byte[2048];
    while (receive) {
        DatagramPacket datagramPacket = new DatagramPacket(data, data.length);
        receiveDatagramSocket.receive(datagramPacket);

        DataResult data1 = UnPacket.getInstance().getData(datagramPacket.getData());
        if (data1 != null && data1.isResult() && data1.getT().getDataType()==Packet.DATA_TYPE_MESSAGE) {
            MessageHandler.getInstance().handleMessage((MessageModel) data1.getT());
        }
    }
}
 
Example 38
Project: NSS   File: CloseMessage_Conn.java   View source code 5 votes vote down vote up
public CloseMessage_Conn(DatagramPacket dp){
	this.dp=dp;
	dpData=dp.getData();
	ver=ByteShortConvert.toShort(dpData, 0);
	sType=ByteShortConvert.toShort(dpData, 2);
	connectId=ByteIntConvert.toInt(dpData, 4);
	clientId=ByteIntConvert.toInt(dpData, 8);
}
 
Example 39
Project: DecompiledMinecraft   File: RConThreadQuery.java   View source code 5 votes vote down vote up
/**
 * Sends an auth challenge DatagramPacket to the client and adds the client to the queryClients map
 */
private void sendAuthChallenge(DatagramPacket requestPacket) throws IOException
{
    RConThreadQuery.Auth rconthreadquery$auth = new RConThreadQuery.Auth(requestPacket);
    this.queryClients.put(requestPacket.getSocketAddress(), rconthreadquery$auth);
    this.sendResponsePacket(rconthreadquery$auth.getChallengeValue(), requestPacket);
}
 
Example 40
Project: thirdcoast   File: ClientHandler.java   View source code 5 votes vote down vote up
/**
 * Start streaming the items specified in the subscription.
 *
 * @param subscription Items to stream to client
 */
public void start(Subscription subscription) {
  if (scheduler != null) {
    return;
  }
  logger.info("Sending graph data to {}:{}", subscription.client(), port);
  socketAddress = new InetSocketAddress(subscription.client(), port);
  scheduler = Executors.newSingleThreadScheduledExecutor();
  // FIXME: future not checked for exception
  ScheduledFuture<?> future =
      scheduler.scheduleAtFixedRate(
          () -> {
            Buffer buffer = new Buffer();
            try {
              subscription.measurementsToJson(buffer);
              byte[] bytes = buffer.readByteArray();
              DatagramPacket packet = new DatagramPacket(bytes, bytes.length, socketAddress);
              socket.send(packet);
            } catch (IOException e) {
              logger.error("Exception sending grapher data", e);
            }
          },
          0,
          5,
          MILLISECONDS);
}