List of usage examples for java.net DatagramPacket getLength
public synchronized int getLength()
From source file:gravity.android.discovery.DiscoveryServer.java
public void run() { Log.v("DISCOVERY_SERVER", "SERVER STARTED"); DatagramSocket serverSocket = null; try {/* w w w . j a va 2 s .c o m*/ serverSocket = new DatagramSocket(port); byte[] receiveData; byte[] sendData; while (this.isInterrupted() == false) { receiveData = new byte[128]; sendData = new byte[128]; try { Log.v("DISCOVERY_SERVER", "LISTENING"); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); if (sentence != null) Log.v("DISCOVERY_SERVER", "RECEIVED: " + sentence.substring(0, receivePacket.getLength()).trim()); if (sentence != null && sentence.substring(0, receivePacket.getLength()).trim().equals(token)) { Log.v("DISCOVERY_SERVER", "SEND '" + nome + "' to " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort()); JSONObject sendDataJson = new JSONObject(); sendDataJson.accumulate("name", nome); sendDataJson.accumulate("port_to_share", port_to_share); //sendData = (nome + "," + port_to_share).getBytes(); sendData = sendDataJson.toString().getBytes(); //Prakash: converts the data to json objects to avoid troubles DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort()); serverSocket.send(sendPacket); } } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_SERVER", ex.toString()); } } } catch (Exception e) { e.printStackTrace(); Log.e("DISCOVERY_SERVER", e.toString()); } finally { try { if (serverSocket != null) serverSocket.close(); } catch (Exception ex) { } } }
From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.distributor.impl.DistributorWorkerImpl.java
@Override @Transactional(readOnly = true)//w w w. j a v a 2 s . co m public void distribute() { try { this.txChecker.checkInTx("DistributorWorker::distribute"); } catch (Throwable e) { e.printStackTrace(); } long currentTime = System.currentTimeMillis(); if (this.logger.isDebugEnabled()) { this.logger.debug("*** Have to distribute <" + this.lastDistributionTime + ", " + currentTime + "]"); } RelayServer me = this.relayServers.getMe(); List<List<Node>> clusters = this.nodes.getClusters(me); if (clusters != null) { for (List<Node> cluster : clusters) { for (Node clusterLeaderNode : cluster) { Sender clusterLeaderNodeSender = clusterLeaderNode.getSender(); if (clusterLeaderNodeSender == null) { this.logger.debug("Cluster leader " + clusterLeaderNode.getMainIp() + " has no sender: skipped to choose a different one"); continue; } RelayServer clusterLeaderNodeRelayServer = clusterLeaderNodeSender.getRelayServer(); if (clusterLeaderNodeRelayServer != me) { this.logger.debug("Cluster leader " + clusterLeaderNode.getMainIp() + " did not report to me: cluster skipped"); break; } if (this.logger.isDebugEnabled()) { this.logger.debug("*** cluster leader " + clusterLeaderNode.getMainIp().getHostAddress() + " (sender=" + clusterLeaderNodeSender.getIp().getHostAddress() + ":" + clusterLeaderNodeSender.getPort() + ")"); } if ((this.myIPAddresses.isMe(clusterLeaderNodeSender.getIp()) || this.myIPAddresses.isMe(clusterLeaderNode.getMainIp())) && (clusterLeaderNodeSender.getPort().intValue() == this.uplinkUdpPort)) { /* do not distribute to ourselves */ if (this.logger.isDebugEnabled()) { this.logger.debug("this is me: skipping"); } break; } List<PositionUpdateMsg> p4ds = this.positions .getPositionUpdateMsgForDistribution(this.lastDistributionTime, currentTime, cluster); if ((p4ds == null) || (p4ds.size() == 0)) { if (this.logger.isDebugEnabled()) { this.logger.debug("p4ds EMPTY"); } break; } if (this.logger.isDebugEnabled()) { StringBuilder s = new StringBuilder(); s.append("p4ds(" + p4ds.size() + ")="); for (PositionUpdateMsg p4d : p4ds) { s.append(" " + p4d.getId()); } this.logger.debug(s.toString()); } List<DatagramPacket> packets = positionUpdateMsgsToPackets(p4ds); if ((packets != null) && (packets.size() > 0)) { StringBuilder s = new StringBuilder(); if (this.logger.isDebugEnabled()) { s.setLength(0); s.append("tx " + packets.size() + " packet(s) to " + clusterLeaderNode.getMainIp().getHostAddress() + " (sender=" + clusterLeaderNodeSender.getIp().getHostAddress() + ":" + clusterLeaderNodeSender.getPort() + "), sizes="); } for (DatagramPacket packet : packets) { if (this.logger.isDebugEnabled()) { s.append(" " + packet.getLength()); } packet.setAddress(clusterLeaderNodeSender.getIp()); packet.setPort(clusterLeaderNodeSender.getPort().intValue()); try { this.sock.send(packet); } catch (IOException e) { if (this.logger.isDebugEnabled()) { s.append(" ERROR:" + e.getLocalizedMessage()); this.logger.debug(s.toString()); } this.logger.error("Could not send to cluster leader " + clusterLeaderNode.getMainIp().getHostAddress() + " (sender=" + clusterLeaderNodeSender.getIp().getHostAddress() + ":" + clusterLeaderNodeSender.getPort() + ") : " + e.getLocalizedMessage()); } } if (this.logger.isDebugEnabled()) { this.logger.debug(s.toString()); } } break; } } } this.lastDistributionTime = currentTime; }
From source file:net.di2e.ddf.argo.probe.responder.ProbeHandler.java
@Override public void run() { LOGGER.debug("Listening for any multicast packets."); String data = ""; while (!isCanceled) { try {/*from w ww .ja v a 2 s . c om*/ byte buf[] = new byte[1024]; DatagramPacket pack = new DatagramPacket(buf, buf.length); socket.receive(pack); data = new String(pack.getData(), pack.getOffset(), pack.getLength()); LOGGER.debug("Packet received with the following payload: {}.", data); Probe probe = JAXB.unmarshal(new StringReader(data), Probe.class); List<RespondTo> respondTo = probe.getRa().getRespondTo(); boolean ignoreProbe = false; if (ignoreProbesList != null && !ignoreProbesList.isEmpty()) { for (String ignoreProbeString : ignoreProbesList) { String updatedIgnoreString = expandRespondToAddress(ignoreProbeString); // TODO cache the request ID and use that instead of the local hostname if (StringUtils.equalsIgnoreCase(updatedIgnoreString, respondTo.get(0).getValue())) { LOGGER.debug( "Configuration is set to ignore probes that have a respondTo of '{}'. Incoming probe contains respondTo of '{}'. IGNORING PROBE.", ignoreProbeString, respondTo.get(0).getValue()); ignoreProbe = true; } } } if (!ignoreProbe) { List<String> contractIDs = probe.getScids().getServiceContractID(); // TODO handle the different contractID // URI contractId = probe.getContractID(); String probeId = probe.getId(); String response = generateServiceResponse(probe.getRespondToPayloadType(), contractIDs, probeId); if (StringUtils.isNotBlank(response)) { LOGGER.debug("Returning back to {} with the following response:\n{}", respondTo.get(0).getValue(), response); sendResponse(respondTo.get(0).getValue(), response, probe.getRespondToPayloadType()); } else { LOGGER.debug( "No services found that match the incoming contract IDs, not sending a response."); } } } catch (DataBindingException e) { LOGGER.warn("Issue parsing probe response: {}", data, e); } catch (SocketTimeoutException ste) { LOGGER.trace("Received timeout on socket, resetting socket to check for cancellation."); } catch (IOException ioe) { if (!isCanceled) { LOGGER.warn("Error while trying to receive a packet, shutting down listener", ioe); } break; } } if (isCanceled) { LOGGER.debug("Listener was canceled, not receiving any more multicast packets."); } }
From source file:org.achartengine.chartdemo.demo.ChartDemo.java
/** * Called when the activity is first created. *//*from w w w.j a va 2s .c o m*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.main); mAppPreferences = new AppPreferences(getApplicationContext()); SmartConnectUtils.setProtraitOrientationEnabled(this); mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe); mSwipeRefreshLayout.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); Log.d(TAG, "Refreshing Number"); (new Handler()).postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); image_details.clear(); listProduct.clear(); mAdapter.notifyDataSetChanged(); } }, 2000); } }); listView_Node = (ListView) findViewById(R.id.listView_Node); /*1. add listview adapter*/ mAdapter = new ItemListBaseAdapter(this, image_details); listView_Node.setAdapter(mAdapter); listView_Node.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { String productType = null; Object o = listView_Node.getItemAtPosition(position); ItemDetails obj_itemDetails = (ItemDetails) o; udpBroadcast.close(); dataSource = obj_itemDetails.getName(); for (Map<String, String> tmp : listProduct) { if (tmp.containsKey(dataSource)) productType = tmp.get(dataSource); } //If id1=2, it means elock; then id1=1, it means wps /* if (productType.equals("2")) { Intent intent = new Intent(ChartDemo.this, ElockActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else if (productType.equals("1")) { Intent intent = new Intent(ChartDemo.this, NumChartActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else if (productType.equals("4")) { Intent intent = new Intent(ChartDemo.this, ScaleActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else*/ if (productType.equals("2")) { Intent intent = new Intent(ChartDemo.this, PlugActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } }); /*2. add a handler*/ mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case AddNode: { Map<String, String> listItem = new HashMap<String, String>(); listItem.put(msg.obj.toString(), String.valueOf(msg.arg1)); listProduct.add(listItem); mAdapter.notifyDataSetChanged(); break; } case START_SEARCH: { if (udpBroadcast.isClosed()) udpBroadcast.open(); udpBroadcast.receive(); mHandler.sendEmptyMessageDelayed(START_SEARCH, DELAY); break; } } } }; /*3. Create one udpbroadcast object*/ udpBroadcast = new udpbroadcast() { private String getDataSource(DatagramPacket datagramPacket) { int i; String data = new String(datagramPacket.getData(), 2, 9); /*check the length of name*/ for (i = 0; i < 9; i++) { if (datagramPacket.getData()[2 + i] == 0) break; } String ssid = new String(datagramPacket.getData(), 2, i); return ssid; } private boolean IsExsits(String SSID) { for (ItemDetails tmp : image_details) { Log.d(TAG, "list node is " + SSID); if (tmp.getName().equals(SSID)) return true; } return false; } /* * typedef struct s_msg_temp_keepalive { * uint8_t id0; * uint8_t id1; * uint8_t name[9]; * uint8_t type; * } t_msg_temp_keepalive; * For PWS: keepalive:id0=0, id1=1; * data report: id0=0, id1=3; * For E-lock: keepalive: id0=0, id1=2; * * For E-scale: keepalive: id0=0, id1=4; * * * * */ @Override public void onReceived(List<DatagramPacket> packets) { for (DatagramPacket packet : packets) { String data = new String(packet.getData(), 0, packet.getLength()); /*Parse ssid*/ if (packet.getData()[0] == 0 && (packet.getData()[1] == 1 || packet.getData()[1] == 2 || packet.getData()[1] == 4 || packet.getData()[1] == 5)) { String tmp_ssid = getDataSource(packet); Log.d(TAG, "Get alive report: " + tmp_ssid); if (IsExsits(tmp_ssid) == false) { Log.d(TAG, "Not exist need add it"); //For JB version it has an extra quote. so need just ignore it. mAppPreferences.setParameter(tmp_ssid, packet.getAddress().toString().substring(1)); ItemDetails item_details = new ItemDetails(); item_details.setName(tmp_ssid); if (packet.getData()[1] == 2) { item_details.setItemDescription("air conditon"); if (packet.getData()[11] == 2) { item_details.setPrice("camera&temperature"); } else if (packet.getData()[11] == 3) { item_details.setPrice("Location: toilet"); } item_details.setImageNumber(2); } image_details.add(item_details); Message msg = mHandler.obtainMessage(AddNode); msg.obj = tmp_ssid; msg.arg1 = packet.getData()[1]; mHandler.sendMessage(msg); } else { } } } } }; /*4. Start auto update search*/ startSearch(); }
From source file:org.zxg.network.dhtcrawler.Crawler.java
@Override protected UdpMsg recvUdp() throws IOException { byte[] buffer = new byte[65536]; DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length); socket.receive(datagramPacket);/*from w ww. j a v a 2 s . c om*/ UdpMsg msg = new UdpMsg(); msg.data = new byte[datagramPacket.getLength()]; System.arraycopy(datagramPacket.getData(), datagramPacket.getOffset(), msg.data, 0, datagramPacket.getLength()); InetSocketAddress socketAddress = (InetSocketAddress) datagramPacket.getSocketAddress(); msg.addr = new Addr(socketAddress.getHostString(), socketAddress.getPort()); return msg; }
From source file:org.jopenray.server.thinclient.DisplayReaderThread.java
@Override public void run() { byte[] buf = new byte[1500]; DatagramPacket packet = new DatagramPacket(buf, buf.length); try {//from w w w.j a v a 2 s .c om while (!this.isInterrupted()) { client.getSocket().receive(packet); handlePacket(buf, packet.getLength()); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
From source file:org.apache.jcs.auxiliary.lateral.socket.tcp.discovery.UDPDiscoveryReceiver.java
/** * Highly unreliable. If it is processing one message while another comes in , * the second message is lost. This is for low concurency peppering. * * @return the object message/*w w w.j av a 2s . c o m*/ * @throws IOException */ public Object waitForMessage() throws IOException { final DatagramPacket packet = new DatagramPacket(m_buffer, m_buffer.length); Object obj = null; try { m_socket.receive(packet); final ByteArrayInputStream byteStream = new ByteArrayInputStream(m_buffer, 0, packet.getLength()); final ObjectInputStream objectStream = new ObjectInputStream(byteStream); obj = objectStream.readObject(); } catch (Exception e) { log.error("Error receving multicast packet", e); } return obj; }
From source file:org.dragonet.net.NetworkHandler.java
private void processPacket(DatagramPacket packet) { try {/*w ww . j a v a 2s . c om*/ PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData())); int raknetPID = reader.readByte() & 0xFF; switch (raknetPID) { case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_1: reader.read(16); //MAGIC reader.readByte(); //RakNet Protocol short mtu = (short) ((packet.getLength() - 18) & 0xFFFF); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_1); writer.write(RaknetConstants.magic); writer.writeLong(NetworkHandler.serverID); writer.writeByte((byte) 0x00); writer.writeShort(mtu); this.udp.send(bos.toByteArray(), packet.getSocketAddress()); break; case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_2: reader.read(16); reader.read(5); reader.readShort(); short clientMTU = reader.readShort(); long clientID = reader.readLong(); ByteArrayOutputStream bos8 = new ByteArrayOutputStream(); PEBinaryWriter writer8 = new PEBinaryWriter(bos8); writer8.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_2); writer8.write(RaknetConstants.magic); writer8.writeLong(NetworkHandler.serverID); writer8.writeShort((short) (packet.getPort() & 0xFFFF)); writer8.writeShort(clientMTU); writer8.writeByte((byte) 0x00); this.send(bos8.toByteArray(), packet.getSocketAddress()); DragonetSession session = new DragonetSession(this.server, packet.getSocketAddress(), clientID, clientMTU); this.sessions.put(packet.getSocketAddress().toString(), session); //this.server.getServer().getSessionRegistry().add(session); break; case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: if (this.sessions.containsKey(packet.getSocketAddress().toString())) { RaknetDataPacket dataPacket = new RaknetDataPacket( ArrayUtils.subarray(packet.getData(), 1, packet.getLength())); dataPacket.decode(); this.sessions.get(packet.getSocketAddress().toString()).processDataPacket(dataPacket); } break; } } catch (IOException e) { } }
From source file:org.avineas.fins.gw.Gateway.java
private void traceDatagram(String prefix, DatagramPacket packet) { if (!logger.isDebugEnabled()) return;/*from w ww . j a v a 2 s . com*/ StringBuffer buffer = new StringBuffer(prefix).append(":"); byte[] data = packet.getData(); int offset = packet.getOffset(); for (int cnt = 0; cnt < packet.getLength(); cnt++) { int thisByte = data[cnt + offset] & 0xff; buffer.append(" ").append(Integer.toHexString(thisByte)); } logger.debug(buffer.toString()); }
From source file:org.eredlab.g4.ccl.net.tftp.TFTPDataPacket.java
/*** * Creates a data packet based from a received * datagram. Assumes the datagram is at least length 4, else an * ArrayIndexOutOfBoundsException may be thrown. * <p>/*from w ww.j a v a 2 s .c o m*/ * @param datagram The datagram containing the received data. * @throws TFTPPacketException If the datagram isn't a valid TFTP * data packet. ***/ TFTPDataPacket(DatagramPacket datagram) throws TFTPPacketException { super(TFTPPacket.DATA, datagram.getAddress(), datagram.getPort()); _data = datagram.getData(); _offset = 4; if (getType() != _data[1]) throw new TFTPPacketException("TFTP operator code does not match type."); _blockNumber = (((_data[2] & 0xff) << 8) | (_data[3] & 0xff)); _length = datagram.getLength() - 4; if (_length > MAX_DATA_LENGTH) _length = MAX_DATA_LENGTH; }