List of usage examples for java.net DatagramPacket getData
public synchronized byte[] getData()
From source file:com.bitbreeds.webrtc.dtls.DtlsMuxStunTransport.java
public int receive(byte[] buf, int off, int len, int waitMillis) throws IOException { socket.setSoTimeout(waitMillis);//from w ww .j av a 2 s . c om DatagramPacket packet = new DatagramPacket(buf, off, len); socket.receive(packet); logger.trace("Socket read msg: {}", Hex.encodeHexString(SignalUtil.copyRange(buf, new ByteRange(0, packet.getLength())))); if (buf.length >= 2 && buf[0] == 0 && buf[1] == 1) { SocketAddress currentSender = packet.getSocketAddress(); byte[] data = Arrays.copyOf(packet.getData(), packet.getLength()); byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(), parent.getLocal().getPassword(), (InetSocketAddress) currentSender); logger.trace("Stun packet received, responding with {}", Hex.encodeHexString(out)); this.send(out, 0, out.length); return 0; //We do not want DTLS to process (not that it will anyway), so we return 0 here. } return packet.getLength(); }
From source file:Networking.Networking.java
/** * Constructs a new {@see #Networking} object. Sets {@see #state} to * {@see Networking.NetworkState#NOT_CONNECTED}, initializes {@see #udpInData} * as array of 512 bytes. Sets {@see #playerPortUDP} to value defined in * {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT} and initializes * {@see udpSocket} with this value as constructor parameter (a port to * bind with this socket). If initialization fails * ({@code SocketException} occurs) increments {@see #playerPortUDP} and * attempts to initialize {@see udpSocket} with parameter {@see #playerPortUDP}. * Proceeds like this until initialization succeeds or until {@see #playerPortUDP} * reaches {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT}{@code + } * {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT_RANGE}{@code - 1}. * Initializes {@see networkListener} as an anonymous {@code Thread} child * with overridden {@code run()} method. * <p> The {@code run()} method/* ww w . j a v a2s . c o m*/ * the greatest part of the network protocol (waits for * {@see edu.cvut.vorobvla.bap.BapMessages#MSG_CALL_FOR_PLAYERS}, processes it * and calls {@see establishConnectionWithModerator} and {@see recvOpts}). * <p>Constructor of {@see #Networking} proceeds with setting {@see #gameListener} * to {@code null}, {@see #broadcastLatestTimestamp} to {@code 0} and * initializing {@see #parser}. * * @throws SocketException if all attempts to initialize {@see udpSocket} * were unsuccessful. */ private Networking() throws SocketException { state = NetworkState.NOT_CONNECTED; this.playerPortUDP = BapPorts.PLAYER_PORT; // identity = Player.getInstance().getName(); udpInData = new byte[512]; while (udpSocket == null) {//may be bug try { udpSocket = new DatagramSocket(playerPortUDP); } catch (SocketException ex) { if (playerPortUDP < BapPorts.PLAYER_PORT + BapPorts.PLAYER_PORT_RANGE) { Logger.getLogger(Networking.class.getName()).log(Level.INFO, "bad UDP port " + playerPortUDP + ". trying another...", "bad UDP port " + playerPortUDP + ". trying another..."); playerPortUDP++; } else { throw new SocketException("no suttable UDP port"); //Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, "no suttable UDP port"); //break; } } } networkListener = new Thread() { @Override public void run() { try { // System.out.println("Start listening to UDP broadcast on" // + udpSocket.getLocalSocketAddress().toString()); DatagramPacket initMsgFromModerator = recvUDP(); String msg = new String(initMsgFromModerator.getData()); if (!msg.split(":")[0].matches(BapMessages.MSG_CALL_FOR_PLAYERS)) { System.err.println("wrong message. got '" + msg + "' while '" + BapMessages.MSG_CALL_FOR_PLAYERS + "' expexted"); return; } System.out.println("RECEVED: " + msg); //get the moderator's IP from the pachage and the port that is listen by it from the message establishConnectionWithModerator(initMsgFromModerator.getAddress(), Integer.parseInt(msg.split(BapMessages.FIELD_DELIM)[1].replaceAll("\\D", ""))); recvOpts(); } catch (IOException ex) { Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, ex); System.err.println("exception while establishing connection"); } } }; gameListener = null; parser = new JSONParser(); broadcastLatestTimestamp = 0; // establishConnectionWithModerator(); }
From source file:org.achartengine.chartdemo.demo.ChartDemo.java
/** * Called when the activity is first created. *//*from w ww .j av a 2 s . c om*/ @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.lwes.listener.DatagramDequeuer.java
protected void handleElement(DatagramQueueElement element) { if (element == null) { return;//w ww. j av a 2s . c o m } DatagramPacket packet = element.getPacket(); if (packet == null) { return; } /* get some metadata */ long timestamp = element.getTimestamp(); IPAddress address = new IPAddress(packet.getAddress()); int port = packet.getPort(); /* now try to deserialize the packet */ try { /* don't validate the event for now to save time */ Event event = factory.createEvent(packet.getData(), false); event.setInt64(Event.RECEIPT_TIME, timestamp); event.setIPAddress(Event.SENDER_IP, address); event.setUInt16(Event.SENDER_PORT, port); if (log.isTraceEnabled()) { log.trace("Dispatching event " + event.toString()); } dispatchEvent(event); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Unable to deserialize event in handleElement()", e); } } }
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 ww w .j a v a2s . c o m*/ 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:cai.flow.collector.Collector.java
/** * * @param p/*from w w w . ja v a2s . co m*/ */ private synchronized void processPacket(final DatagramPacket p) { final byte[] buf = p.getData(); int len = p.getLength(); String addr = p.getAddress().getHostAddress().trim(); synchronized (data_queue) { processed++; } logger.debug(addr + "(" + p.getAddress().getHostName() + ") " + len + " bytes"); try { if (len < 2) throw new DoneException(" * too short packet *"); short version = (short) Util.to_number(buf, 0, 2); if (version > MAX_VERION || version <= 0) throw new DoneException(" * unsupported version *"); if (!isVersionEnabled[version - 1]) throw new DoneException(" * version " + version + " disabled *"); logger.debug(" version: " + version); FlowPacket packet; switch (version) { case 1: packet = (FlowPacket) new V1_Packet(addr, buf, len); break; case 5: packet = (FlowPacket) new V5_Packet(addr, buf, len); break; // Temporarily removing NetFlow Version 7 until Resources fully removed /* case 7: packet = (FlowPacket) new V7_Packet(addr, resources, buf, len); break; */ case 8: packet = (FlowPacket) new V8_Packet(addr, buf, len); break; case 9: packet = (FlowPacket) new V9_Packet(addr, buf, len); break; default: logger.error("Collector - Version problem. Version = " + version); return; } aggregator.process(packet); } catch (DoneException e) { e.printStackTrace(); logger.info(e); } }
From source file:udpserver.UDPui.java
private void tempReceiveUDP() { background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }/*from w w w .j a v a 2s.c om*/ // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String word = serverSocket.getInetAddress().toString(); // Integer count = counting.get(word); // if (count == null) { // counting.put(word, 1); // } // else { // counting.put(word, count + 1); // } boolean looprun = true; String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); // System.out.println(message); while (looprun) { if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); Integer count = counting.get(word); if (count == null) { counting.put(word, 2); } else { counting.put(word, count + 1); } // System.out.println(count + ":" + message); } else { looprun = false; } } if (message.equals("end")) { valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); //end send back to mobile // count = 1; // break; counting.remove(word); } else if (available) { // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); } } // } // } } }; backgroundProcess = new Thread(background); }
From source file:org.opennms.netmgt.syslogd.ConvertToEvent.java
/** * Constructs a new event encapsulation instance based upon the * information passed to the method. The passed datagram data is decoded * into a string using the <tt>US-ASCII</tt> character encoding. * * @param packet The datagram received from the remote agent. * @throws java.io.UnsupportedEncodingException * Thrown if the data buffer cannot be decoded using the * US-ASCII encoding./*w w w . j ava2s . c o m*/ * @throws MessageDiscardedException */ public ConvertToEvent(final DatagramPacket packet, final SyslogdConfig config) throws UnsupportedEncodingException, MessageDiscardedException { this(packet.getAddress(), packet.getPort(), new String(packet.getData(), 0, packet.getLength(), "US-ASCII"), config); }
From source file:com.webobjects.monitor.application.HostsPage.java
private boolean hostMeetsMinimumVersion(InetAddress anAddress) { byte[] versionRequest; try {// www.j a v a 2s.co m versionRequest = ("womp://queryVersion").getBytes(CharEncoding.UTF_8); } catch (UnsupportedEncodingException uee) { versionRequest = ("womp://queryVersion").getBytes(); } DatagramPacket outgoingPacket = new DatagramPacket(versionRequest, versionRequest.length, anAddress, WOApplication.application().lifebeatDestinationPort()); byte[] mbuffer = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(mbuffer, mbuffer.length); DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.send(outgoingPacket); incomingPacket.setLength(mbuffer.length); socket.setSoTimeout(2000); socket.receive(incomingPacket); String reply = new String(incomingPacket.getData()); if (reply.startsWith("womp://replyVersion/")) { int lastIndex = reply.lastIndexOf(":webObjects"); lastIndex += 11; String version = reply.substring(lastIndex); if (version.equals("4.5")) { return false; } } else { return false; } } catch (InterruptedIOException iioe) { return true; } catch (SocketException se) { return true; } catch (Throwable e) { return false; } finally { if (socket != null) { socket.close(); } } return true; }
From source file:org.apache.jmeter.JMeter.java
private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) { byte[] buf = new byte[80]; System.out.println(/*from www. j a v a 2s . c o m*/ "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort()); DatagramPacket request = new DatagramPacket(buf, buf.length); try { while (true) { socket.receive(request); InetAddress address = request.getAddress(); // Only accept commands from the local host if (address.isLoopbackAddress()) { String command = new String(request.getData(), request.getOffset(), request.getLength(), "ASCII"); System.out.println("Command: " + command + " received from " + address); log.info("Command: " + command + " received from " + address); if (command.equals("StopTestNow")) { for (JMeterEngine engine : engines) { engine.stopTest(true); } } else if (command.equals("Shutdown")) { for (JMeterEngine engine : engines) { engine.stopTest(false); } } else if (command.equals("HeapDump")) { HeapDumper.dumpHeap(); } else { System.out.println("Command: " + command + " not recognised "); } } } } catch (Exception e) { System.out.println(e); } finally { socket.close(); } }