List of usage examples for java.net DatagramSocket send
public void send(DatagramPacket p) throws IOException
From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java
/** * WSIAdapter interface//from ww w . ja v a 2s. c o m */ public List<Node> getAvailableNodeList() throws WSIAdapterException { logger.info("Getting available nodes..."); nodesList = new ArrayList<Node>(); List<String> wsnProxyList = new LinkedList<String>(); wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS); wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS); DatagramSocket serverSocket = null; DatagramSocket clientSocket = null; String cmdString = "route"; for (int i = 0; i < wsnProxyList.size(); i++) { try { serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT); String hostProxyString = wsnProxyList.get(i); InetAddress hostProxy = InetAddress.getByName(hostProxyString); clientSocket = new DatagramSocket(); byte[] bufCmd = new byte[10]; bufCmd = cmdString.getBytes(); DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy, Constants.PROXY_UDPFORWARDER_PORT); clientSocket.send(outcomingPacket); boolean otherPackets = false; serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT); logger.info("Quering " + hostProxyString); try { byte[] bufAck = new byte[10]; DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length); serverSocket.receive(ackPacket); String ackString = new String(ackPacket.getData()).trim(); if (ackString.equals("ack")) { otherPackets = true; } } catch (SocketTimeoutException e) { logger.warn(e.getMessage()); } serverSocket.setSoTimeout(0); while (otherPackets) { try { byte[] bufIncoming = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length); serverSocket.receive(incomingPacket); String currentNodeIP = new String(incomingPacket.getData()).trim(); if (!currentNodeIP.equals("end")) { logger.info("Node: " + currentNodeIP); nodesList.add(new Node(currentNodeIP)); } else { otherPackets = false; logger.info("No other nodes from " + hostProxyString); } } catch (IOException e) { logger.error(e.getMessage()); } } } catch (UnknownHostException e) { logger.warn(e.getMessage() + " is not reachable."); } catch (SocketException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { if (serverSocket != null) { serverSocket.close(); } if (clientSocket != null) { clientSocket.close(); } } } return nodesList; }
From source file:snapshotTools.java
private String callOvnmanager(String node, String action) { String result = ""; DatagramSocket socket = null; int serverPort = 9999; DatagramPacket packet2Send;//from w w w . ja va 2 s .co m DatagramPacket receivedPacket; InetAddress theServerAddress; byte[] outBuffer; byte[] inBuffer; inBuffer = new byte[8192]; outBuffer = new byte[8192]; try { HttpSession session = RuntimeAccess.getInstance().getSession(); String sessionUser = (String) session.getAttribute("User"); if (sessionUser == null) { sessionUser = "administrator"; } JSONObject joCmd = new JSONObject(); JSONObject joAction = new JSONObject(action); joCmd.put("sender", sessionUser); joCmd.put("target", "SNAPSHOT"); joCmd.put("node", node); joCmd.put("action", joAction); String output = joCmd.toString(); socket = new DatagramSocket(); String actionName = joAction.get("name").toString(); if (actionName.equals("create")) { socket.setSoTimeout(180000); } else { socket.setSoTimeout(60000); } InetAddress serverInet = InetAddress.getByName("localhost"); socket.connect(serverInet, serverPort); outBuffer = output.getBytes(); packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort); try { // send the data socket.send(packet2Send); receivedPacket = new DatagramPacket(inBuffer, inBuffer.length); socket.receive(receivedPacket); // the server response is... result = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); session.setAttribute("LastActive", System.currentTimeMillis()); } catch (Exception excep) { String msg = excep.getMessage(); //String msg = excep.toString(); joCmd.remove("action"); joAction.put("result", "Error:" + msg); joCmd.put("action", joAction); result = joCmd.toString(); } socket.close(); } catch (Exception e) { log(ERROR, "callOvnmanager", e); return e.toString(); } return result; }
From source file:gravity.android.discovery.DiscoveryServer.java
public void run() { Log.v("DISCOVERY_SERVER", "SERVER STARTED"); DatagramSocket serverSocket = null; try {/*from w ww.ja va2 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:org.echocat.jomon.net.dns.DnsServer.java
public void serveUDP(InetSocketAddress address) { try {/* w ww .j a v a2 s . c om*/ final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress()); synchronized (_closeables) { _closeables.add(sock); } final short udpLength = 512; final byte[] in = new byte[udpLength]; final DatagramPacket indp = new DatagramPacket(in, in.length); DatagramPacket outdp = null; while (!currentThread().isInterrupted()) { indp.setLength(in.length); receive(sock, indp); final Message query; byte[] response; try { query = new Message(in); response = generateReply(query, in, indp.getLength(), null); if (response == null) { continue; } } catch (final IOException ignored) { response = formerrMessage(in); } if (outdp == null) { outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort()); } else { outdp.setData(response); outdp.setLength(response.length); outdp.setAddress(indp.getAddress()); outdp.setPort(indp.getPort()); } sock.send(outdp); } } catch (final InterruptedIOException ignored) { currentThread().interrupt(); } catch (final IOException e) { LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e); } }
From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString/*w ww . j ava 2s .c o m*/ * String to be used for the discovery */ private void sendDiscoveryMessage(String discoverString) { DatagramSocket bcSend = null; try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = discoverString.getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = null; if (StringUtils.isNotBlank(optionalHost)) { try { broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) }; } catch (Exception e) { logger.error("Could not use host for hub discovery", e); return; } } else { broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"), InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() }; } for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, DISCO_PORT); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } catch (Exception e) { logger.debug(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { // Ignore } } }
From source file:CTmousetrack.java
public static void main(String[] args) { String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder String srcName = "CTmousetrack"; // name of the output CT source long blockPts = 10; // points per block flush long sampInterval = 10; // time between sampling updates, msec double trimTime = 0.0; // amount of data to keep (trim time), sec boolean debug = false; // turn on debug? // Specify the CT output connection CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data String serverHost = ""; // Server (FTP or HTTP/S) host:port String serverUser = ""; // Server (FTP or HTTPS) username String serverPassword = ""; // Server (FTP or HTTPS) password // For UDP output mode DatagramSocket udpServerSocket = null; InetAddress udpServerAddress = null; String udpHost = ""; int udpPort = -1; // Concatenate all of the CTWriteMode types String possibleWriteModes = ""; for (CTWriteMode wm : CTWriteMode.values()) { possibleWriteModes = possibleWriteModes + ", " + wm.name(); }/*from w w w . j a v a 2s. c o m*/ // Remove ", " from start of string possibleWriteModes = possibleWriteModes.substring(2); // // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption(Option.builder("o").argName("base output dir").hasArg().desc( "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \"" + outLoc + "\".") .build()); options.addOption(Option.builder("s").argName("source name").hasArg() .desc("Name of source to write data to; default = \"" + srcName + "\".").build()); options.addOption(Option.builder("b").argName("points per block").hasArg() .desc("Number of points per block; UDP output mode will use 1 point/block; default = " + Long.toString(blockPts) + ".") .build()); options.addOption(Option.builder("dt").argName("samp interval msec").hasArg() .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build()); options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc( "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption( Option.builder("w").argName("write mode").hasArg() .desc("Type of write connection; one of " + possibleWriteModes + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".") .build()); options.addOption(Option.builder("host").argName("host[:port]").hasArg() .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build()); options.addOption(Option.builder("u").argName("username,password").hasArg() .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build()); options.addOption("x", "debug", false, "Enable CloudTurbine debug output."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("CTmousetrack", "", options, "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port."); return; } outLoc = line.getOptionValue("o", outLoc); if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) { outLoc = outLoc + File.separator; } // Make sure the base output folder location ends in "CTdata" if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) { outLoc = outLoc + "CTdata" + File.separator; } srcName = line.getOptionValue("s", srcName); blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts))); sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval))); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); // Type of output connection String writeModeStr = line.getOptionValue("w", writeMode.name()); boolean bMatch = false; for (CTWriteMode wm : CTWriteMode.values()) { if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) { writeMode = wm; bMatch = true; } } if (!bMatch) { System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of " + possibleWriteModes); System.exit(0); } if (writeMode != CTWriteMode.LOCAL) { // User must have specified the host // If FTP or HTTPS, they may also specify username/password serverHost = line.getOptionValue("host", serverHost); if (serverHost.isEmpty()) { System.err.println( "When using write mode \"" + writeModeStr + "\", you must specify the server host."); System.exit(0); } if (writeMode == CTWriteMode.UDP) { // Force blockPts to be 1 blockPts = 1; // User must have specified both host and port int colonIdx = serverHost.indexOf(':'); if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) { System.err.println( "For UDP output mode, both the host and port (<host>:<port>)) must be specified."); System.exit(0); } udpHost = serverHost.substring(0, colonIdx); String udpPortStr = serverHost.substring(colonIdx + 1); try { udpPort = Integer.parseInt(udpPortStr); } catch (NumberFormatException nfe) { System.err.println("The UDP port must be a positive integer."); System.exit(0); } } if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) { String userpassStr = line.getOptionValue("u", ""); if (!userpassStr.isEmpty()) { // This string should be comma-delimited username and password String[] userpassCSV = userpassStr.split(","); if (userpassCSV.length != 2) { System.err.println("When specifying a username and password for write mode \"" + writeModeStr + "\", separate the username and password by a comma."); System.exit(0); } serverUser = userpassCSV[0]; serverPassword = userpassCSV[1]; } } } debug = line.hasOption("debug"); System.err.println("CTmousetrack parameters:"); System.err.println("\toutput mode = " + writeMode.name()); if (writeMode == CTWriteMode.UDP) { System.err.println("\twrite to " + udpHost + ":" + udpPort); } else { System.err.println("\tsource = " + srcName); System.err.println("\ttrim time = " + trimTime + " sec"); } System.err.println("\tpoints per block = " + blockPts); System.err.println("\tsample interval = " + sampInterval + " msec"); try { // // Setup CTwriter or UDP output // CTwriter ctw = null; CTinfo.setDebug(debug); if (writeMode == CTWriteMode.LOCAL) { ctw = new CTwriter(outLoc + srcName, trimTime); System.err.println("\tdata will be written to local folder \"" + outLoc + "\""); } else if (writeMode == CTWriteMode.FTP) { CTftp ctftp = new CTftp(srcName); try { ctftp.login(serverHost, serverUser, serverPassword); } catch (Exception e) { throw new IOException( new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage())); } ctw = ctftp; // upcast to CTWriter System.err.println("\tdata will be written to FTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTP) { // Don't send username/pw in HTTP mode since they will be unencrypted CThttp cthttp = new CThttp(srcName, "http://" + serverHost); ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTPS) { CThttp cthttp = new CThttp(srcName, "https://" + serverHost); // Username/pw are optional for HTTPS mode; only use them if username is not empty if (!serverUser.isEmpty()) { try { cthttp.login(serverUser, serverPassword); } catch (Exception e) { throw new IOException(new String( "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage())); } } ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTPS server at " + serverHost); } else if (writeMode == CTWriteMode.UDP) { try { udpServerSocket = new DatagramSocket(); } catch (SocketException se) { System.err.println("Error creating socket for UDP:\n" + se); System.exit(0); } try { udpServerAddress = InetAddress.getByName(udpHost); } catch (UnknownHostException uhe) { System.err.println("Error getting UDP server host address:\n" + uhe); System.exit(0); } } if (writeMode != CTWriteMode.UDP) { ctw.setBlockMode(blockPts > 1, blockPts > 1); ctw.autoFlush(0); // no autoflush ctw.autoSegment(1000); } // screen dims Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); // use Map for consolidated putData Map<String, Object> cmap = new LinkedHashMap<String, Object>(); // loop and write some output for (int i = 0; i < 1000000; i++) { // go until killed long currentTime = System.currentTimeMillis(); Point mousePos = MouseInfo.getPointerInfo().getLocation(); float x_pt = (float) (mousePos.getX() / width); // normalize float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0) if (writeMode != CTWriteMode.UDP) { // CT output mode ctw.setTime(currentTime); cmap.clear(); cmap.put("x", x_pt); cmap.put("y", y_pt); ctw.putData(cmap); if (((i + 1) % blockPts) == 0) { ctw.flush(); System.err.print("."); } } else { // UDP output mode // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time // Write the following data (21 bytes total): // header = "MOUSE", 5 bytes // current time, long, 8 bytes // 2 floats (x,y) 4 bytes each, 8 bytes int len = 21; ByteBuffer bb = ByteBuffer.allocate(len); String headerStr = "MOUSE"; bb.put(headerStr.getBytes("UTF-8")); bb.putLong(currentTime); bb.putFloat(x_pt); bb.putFloat(y_pt); // Might be able to use the following, but not sure: // byte[] sendData = bb.array(); byte[] sendData = new byte[len]; bb.position(0); bb.get(sendData, 0, len); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress, udpPort); try { udpServerSocket.send(sendPacket); } catch (IOException e) { System.err.println("Test server caught exception trying to send data to UDP client:\n" + e); } System.err.print("."); } try { Thread.sleep(sampInterval); } catch (Exception e) { } ; } if (writeMode != CTWriteMode.UDP) { ctw.flush(); // wrap up } } catch (Exception e) { System.err.println("CTmousetrack exception: " + e); e.printStackTrace(); } }
From source file:vmXmlFile.java
private String callOvnmanager(String node, String action) { String result = ""; DatagramSocket socket = null; int serverPort = 9999; DatagramPacket packet2Send;//from w w w. j a v a 2 s .c om DatagramPacket receivedPacket; InetAddress theServerAddress; byte[] outBuffer; byte[] inBuffer; inBuffer = new byte[65536]; outBuffer = new byte[8192]; try { HttpSession session = RuntimeAccess.getInstance().getSession(); String sessionUser = (String) session.getAttribute("User"); if (sessionUser == null) { sessionUser = "administrator"; } JSONObject joCmd = new JSONObject(); JSONObject joAction = new JSONObject(action); joCmd.put("sender", sessionUser); joCmd.put("target", "VM"); joCmd.put("node", node); joCmd.put("action", joAction); String output = joCmd.toString(); socket = new DatagramSocket(); InetAddress serverInet = InetAddress.getByName("localhost"); socket.connect(serverInet, serverPort); outBuffer = output.getBytes(); packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort); // send the data socket.send(packet2Send); receivedPacket = new DatagramPacket(inBuffer, inBuffer.length); socket.receive(receivedPacket); // the server response is... result = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); session.setAttribute("LastActive", System.currentTimeMillis()); socket.close(); } catch (Exception e) { log(ERROR, "callOvnmanager", e); return e.toString(); } return result; }
From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java
@Override public void run() { MulticastSocket recvSocket = null; // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe. DatagramSocket sendSocket = null; byte[] buf = new byte[1000]; DatagramPacket recv = new DatagramPacket(buf, buf.length); while (running) { try {//from www . ja v a 2 s . c o m if (discoveryIp != null && discoveryIp.trim().length() > 0) { address = InetAddress.getByName(discoveryIp); } else { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) { address = addr; break; } } } } InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV); recvSocket = new MulticastSocket(UPNP_PORT_RECV); recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address)); sendSocket = new DatagramSocket(); while (running) { recvSocket.receive(recv); if (recv.getLength() > 0) { String data = new String(recv.getData()); logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(), recv.getPort()); if (data.startsWith("M-SEARCH")) { String msg = String.format(discoString, "http://" + address.getHostAddress().toString() + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn); DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(), recv.getAddress(), recv.getPort()); try { logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg); sendSocket.send(response); } catch (IOException e) { logger.error("Could not send UPNP response", e); } } } } } catch (SocketException e) { logger.error("Socket error with UPNP server", e); } catch (IOException e) { logger.error("IO Error with UPNP server", e); } finally { IOUtils.closeQuietly(recvSocket); IOUtils.closeQuietly(sendSocket); if (running) { try { Thread.sleep(3000); } catch (InterruptedException e) { } } } } }
From source file:vmTools.java
private String callOvnmanager(String node, String action) { String result = ""; DatagramSocket socket = null; int serverPort = 9999; DatagramPacket packet2Send;//from www. j av a 2s .c om DatagramPacket receivedPacket; InetAddress theServerAddress; byte[] outBuffer; byte[] inBuffer; inBuffer = new byte[65536]; outBuffer = new byte[8192]; /* if (this.user == null) { this.user = "admin"; }*/ try { HttpSession session = RuntimeAccess.getInstance().getSession(); String sessionUser = (String) session.getAttribute("User"); if (sessionUser == null) { sessionUser = "administrator"; } JSONObject joCmd = new JSONObject(); JSONObject joAction = new JSONObject(action); joCmd.put("sender", sessionUser); joCmd.put("target", "VM"); joCmd.put("node", node); joCmd.put("action", joAction); String output = joCmd.toString(); socket = new DatagramSocket(); String actionName = joAction.get("name").toString(); /*if (actionName.equals("migrate")) { socket.setSoTimeout(600000); } else { socket.setSoTimeout(60000); }*/ socket.setSoTimeout(60000); InetAddress serverInet = InetAddress.getByName("localhost"); socket.connect(serverInet, serverPort); outBuffer = output.getBytes(); packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort); try { // send the data socket.send(packet2Send); receivedPacket = new DatagramPacket(inBuffer, inBuffer.length); socket.receive(receivedPacket); // the server response is... result = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); session.setAttribute("LastActive", System.currentTimeMillis()); } catch (Exception excep) { String msg = excep.getMessage(); //String msg = excep.toString(); joCmd.remove("action"); joAction.put("result", "Error:" + msg); joCmd.put("action", joAction); result = joCmd.toString(); } socket.close(); } catch (Exception e) { log(ERROR, "callOvnmanager", e); return e.toString(); } return result; }
From source file:serverTools.java
private String callOvnmanager(String node, String action) { String result = ""; DatagramSocket socket = null; int serverPort = 9999; DatagramPacket packet2Send;/*from w w w . ja v a2 s . co m*/ DatagramPacket receivedPacket; InetAddress theServerAddress; byte[] outBuffer; byte[] inBuffer; //inBuffer = new byte[8192]; //outBuffer = new byte[8192]; inBuffer = new byte[65536]; outBuffer = new byte[8192]; try { HttpSession session = RuntimeAccess.getInstance().getSession(); String sessionUser = (String) session.getAttribute("User"); if (sessionUser == null) { sessionUser = "administrator"; } JSONObject joAction = new JSONObject(action); JSONObject joCmd = new JSONObject(); joCmd.put("sender", sessionUser); joCmd.put("target", "NODE"); joCmd.put("node", node); joCmd.put("action", joAction); String output = joCmd.toString(); socket = new DatagramSocket(); // set timeout String actionName = joAction.get("name").toString(); if (actionName.equals("add")) { socket.setSoTimeout(90000); } else if (actionName.equals("connect")) { socket.setSoTimeout(60000); } else { socket.setSoTimeout(60000); } InetAddress serverInet = InetAddress.getByName("localhost"); socket.connect(serverInet, serverPort); outBuffer = output.getBytes(); packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort); receivedPacket = new DatagramPacket(inBuffer, inBuffer.length); try { // send the data socket.send(packet2Send); // receive reply socket.receive(receivedPacket); // the server reply is... result = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); session.setAttribute("LastActive", System.currentTimeMillis()); } catch (Exception excep) { String msg = excep.getMessage(); //String msg = excep.toString(); joCmd.remove("action"); joAction.put("result", "Error:" + msg); joCmd.put("action", joAction); result = joCmd.toString(); } socket.close(); } catch (Exception e) { log(ERROR, "callOvnmanager", e); return e.toString(); } return result; }