List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:pl.edu.agh.BackgroundServiceConnection.java
/** * Compares sent hash to the one in database *///from w ww. j a va 2 s . c o m public void run() { while (true) { try { LOGGER.info("Accepting connections on port: " + serverPort); Socket client = serverSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String message = in.readLine(); DataOutputStream out = new DataOutputStream(client.getOutputStream()); LOGGER.info("Daemon message: " + message); String[] data = message.trim().split("\\|"); try { Service service = serviceDAO.getById(Integer.parseInt(data[1])); if (!data[0].equalsIgnoreCase(service.getPassword())) throw new IllegalArgumentException("Daemon password: " + data[0] + " does not match server password: " + service.getPassword()); out.writeBytes("OK\r\n"); } catch (Exception e) { LOGGER.error("Could not find server: " + message.trim(), e); out.writeBytes("ERROR\r\n"); } in.close(); out.close(); client.close(); } catch (Exception e) { LOGGER.error("Error connecting with server: " + e.getMessage()); } } }
From source file:com.annuletconsulting.homecommand.node.AsyncSend.java
@Override public Loader<String> onCreateLoader(int id, Bundle args) { AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) { @Override//from w w w. j a va2 s . co m public String loadInBackground() { StringBuffer instr = new StringBuffer(); try { Socket connection = new Socket(ipAddr, port); BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII"); osw.write(formatJSON(command.toUpperCase())); osw.write(13); osw.flush(); BufferedInputStream bis = new BufferedInputStream(connection.getInputStream()); InputStreamReader isr = new InputStreamReader(bis, "US-ASCII"); int c; while ((c = isr.read()) != 13) instr.append((char) c); isr.close(); bis.close(); osw.close(); bos.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } return instr.toString(); } }; return loader; }
From source file:edu.umd.cs.marmoset.utilities.UptimeDaemon.java
public void run() { // Listen on a socket for connections and report the current uptime Thread t = new Thread() { @Override//w w w . ja v a 2s. com public void run() { while (true) { try { Socket sock = serverSocket.accept(); String uptime = shellCommand("uptime"); sock.getOutputStream().write(uptime.getBytes()); sock.close(); } catch (IOException e) { System.out.println(e); e.printStackTrace(); } catch (InterruptedException e) { System.out.println(e); e.printStackTrace(); } } } }; t.start(); //if (false) new Thread() { @Override public void run() { while (true) { try { String uptime = shellCommand("uptime"); //System.out.println(uptime); processLoad(uptime); Thread.sleep(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); }
From source file:com.iitb.cse.ConnectionInfo.java
static void handleConnection(Socket sock, Session session, int tid) { System.out.println("\n\n\n---------------->>>>>>>>>[" + tid + "]"); try {/*from w w w . ja v a2s . c om*/ int count = 0; boolean newConnection = true; String ip_add = sock.getInetAddress().toString(); String[] _ip_add = ip_add.split("/"); String macAddress = ""; DeviceInfo myDevice = null; InputStream in = sock.getInputStream(); OutputStream out = sock.getOutputStream(); DataInputStream dis = new DataInputStream(in); DataOutputStream dos = new DataOutputStream(out); while (true) { System.out.println("\n[" + tid + "] My Socket : " + sock); String receivedData = ClientConnection.readFromStream(sock, dis, dos).trim(); if (receivedData.equals("") || receivedData == null) { System.out.println("\n[Empty/Null Data][" + tid + "]"); } else { System.out.println("\nReceived : " + receivedData); Map<String, String> jsonMap = null; JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { @SuppressWarnings("rawtypes") @Override public List creatArrayContainer() { return new LinkedList(); } @SuppressWarnings("rawtypes") @Override public Map createObjectContainer() { return new LinkedHashMap(); } }; try { jsonMap = (Map<String, String>) parser.parse(receivedData, containerFactory); if (jsonMap != null) { String action = jsonMap.get(Constants.action); if (action.compareTo(Constants.heartBeat) == 0 || action.compareTo(Constants.heartBeat1) == 0 || action.compareTo(Constants.heartBeat2) == 0) { macAddress = jsonMap.get(Constants.macAddress); // heartbeat System.out.println("\n [" + tid + "] HeartBeat Received : " + (++count)); DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress)); if (device == null) { // first time from this device. ie new connection System.out.println("<<<== 1 ==>>>"); DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); newDevice.setBssid(jsonMap.get(Constants.bssid)); newDevice.setSsid(jsonMap.get(Constants.ssid)); // newDevice.setSsid(jsonMap.get(Constants.bssidList)); /* String apInfo = jsonMap.get(Constants.bssidList); if (apInfo != null || !apInfo.equals("")) { System.out.println("\nInside Bssid List1"); String[] bssidInfo = apInfo.split(";"); NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length]; for (int i = 0; i < bssidInfo.length; i++) { String[] info = bssidInfo[i].split(","); obj[i].setBssid(info[0]); obj[i].setRssi(info[1]); obj[i].setRssi(info[2]); } newDevice.setBssidList(obj); }*/ Date date = Utils.getCurrentTimeStamp(); newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setConnectionStatus(true); newDevice.setThread(Thread.currentThread()); newDevice.setSocket(sock); newDevice.setGetlogrequestsend(false); /* remaining parameters needs to be added!!! */ session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); } else // subsequent heartbeats / reconnection from same client if (newConnection) { // reconnection from same client System.out.println("<<<== 2 ==>>>"); if (device.thread != null) { device.thread.interrupt(); System.out.println("\n@#1[" + tid + "] Interrupting old thread"); } DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); newDevice.setBssid(jsonMap.get(Constants.bssid)); newDevice.setSsid(jsonMap.get(Constants.ssid)); /* String apInfo = jsonMap.get(Constants.bssidList); if (apInfo != null || !apInfo.equals("")) { System.out.println("\nInside Bssid List"); String[] bssidInfo = apInfo.split(";"); NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length]; for (int i = 0; i < bssidInfo.length; i++) { String[] info = bssidInfo[i].split(","); obj[i].setBssid(info[0]); obj[i].setRssi(info[1]); obj[i].setRssi(info[2]); } newDevice.setBssidList(obj); }*/ Date date = Utils.getCurrentTimeStamp(); newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setSocket(sock); newDevice.setThread(Thread.currentThread()); newDevice.setConnectionStatus(true); newDevice.setGetlogrequestsend(false); /* remaining parameters needs to be added!!! */ session.connectedClients.remove(device.macAddress); session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); if (session.filteredClients.contains(device)) { session.filteredClients.remove(device); session.filteredClients.add(newDevice); } } else { // heartbeat System.out.println("<<<== 3 ==>>>"); Date date = Utils.getCurrentTimeStamp(); device.setLastHeartBeatTime(date); device.setSocket(sock); device.setConnectionStatus(true); } } else if (action.compareTo(Constants.experimentOver) == 0) { macAddress = jsonMap.get(Constants.macAddress); System.out.println("\n[" + tid + "] Experiment Over Mesage received"); // experiment over // i need mac address from here // ip and port also preferred DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress)); if (device == null) { // new connection System.out.println("<<<== 4 ==>>>"); DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); //Date date = Utils.getCurrentTimeStamp(); //newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setSocket(sock); newDevice.setThread(Thread.currentThread()); newDevice.setGetlogrequestsend(false); newDevice.setConnectionStatus(true); newDevice.setExpOver(1); // if (DBManager.updateExperimentOverStatus( Integer.parseInt(jsonMap.get(Constants.experimentNumber)), newDevice.getMacAddress())) { System.out.println("\nDB Update ExpOver Success"); } else { System.out.println("\nDB Update ExpOver Failed"); } /* remaining parameters needs to be added!!! */ session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); } else if (newConnection) { // reconnction from the same client System.out.println("<<<== 5 ==>>>"); if (device.thread != null) { device.thread.interrupt(); System.out.println("\n@#2[" + tid + "] Interrupting old thread"); } DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); //Date date = Utils.getCurrentTimeStamp(); //newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setSocket(sock); newDevice.setThread(Thread.currentThread()); newDevice.setGetlogrequestsend(false); newDevice.setConnectionStatus(true); /* remaining parameters needs to be added!!! */ newDevice.setExpOver(1); // if (DBManager.updateExperimentOverStatus( Integer.parseInt(jsonMap.get(Constants.experimentNumber)), newDevice.getMacAddress())) { System.out.println("\nDB Update ExpOver Success"); } else { System.out.println("\nDB Update ExpOver Failed"); } session.connectedClients.remove(device.macAddress); session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); if (session.filteredClients.contains(device)) { session.filteredClients.remove(device); session.filteredClients.add(newDevice); } } else { System.out.println("<<<== 6 ==>>>"); // alread connected client // device.setExpOver(jsonMap.get(Constants.macAddress)) device.setConnectionStatus(true); device.setSocket(sock); device.setExpOver(1); // if (DBManager.updateExperimentOverStatus( Integer.parseInt(jsonMap.get(Constants.experimentNumber)), device.getMacAddress())) { System.out.println("\nDB Update ExpOver Success"); } else { System.out.println("\nDB Update ExpOver Failed"); } } } else if (action.compareTo(Constants.acknowledgement) == 0) { System.out.println("\nAcknowledgement Received -->"); int expNumber = Integer.parseInt(jsonMap.get(Constants.experimentNumber)); System.out.println("\nExperiment number : " + expNumber); //int sessionId = Utils.getCurrentSessionID(); int expId = 1; ///important int expId =1;// Utils.getCurrentExperimentID(Integer.toString(1)); System.out.println("\nExperiment number : " + expNumber + "== " + expId); // if (expNumber == expId) { if (macAddress != null && !macAddress.equals("")) { DeviceInfo device = session.connectedClients.get(macAddress); session.actualFilteredDevices.add(device); System.out.println("\n Ack : " + expNumber + " Acknowledgement Received!!!"); if (DBManager.updateControlFileSendStatus(expNumber, macAddress, 1, "Successfully sent Control File")) { System.out.println("\n Ack : " + expNumber + " DB updated Successfully"); } else { System.out.println("\n Ack : " + expNumber + " DB updation Failed"); } ///important Utils.addExperimentDetails(expId, device, false); } // } // update the db. } else { System.out.println("\n[" + tid + "] Some Other Operation..."); } newConnection = false; } } catch (Exception ex) { System.out.println("Json Ex : " + ex.toString()); } } try { Thread.sleep(5000); // wait for interrupt } catch (InterruptedException ex) { System.out.println("\n[" + tid + "] InterruptedException 1 : " + ex.toString() + "\n"); try { sock.close(); } catch (IOException ex1) { System.out.println("\n[" + tid + "] IOException5 : " + ex1.toString() + "\n"); } break; // } } } catch (IOException ex) { System.out.println("\n [" + tid + "] IOException1 : " + ex.toString() + "\n"); try { sock.close(); // session.connectedClients.remove(conn); } catch (IOException ex1) { System.out.println("\n[" + tid + "] IOException2 : " + ex1.toString() + "\n"); } } catch (Exception ex) { System.out.println("\n[" + tid + "] IOException3 : " + ex.toString() + "\n"); try { sock.close(); // session.connectedClients.remove(conn); } catch (IOException ex1) { System.out.println("\n[" + tid + "] IOException4 : " + ex1.toString() + "\n"); } } }
From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java
protected String sendMessage(String message) throws IOException { LOG.info("sending message '" + message + "'"); Socket socket = new Socket("localhost", 1111); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); out.write((message + '\n').getBytes(StandardCharsets.UTF_8)); String response = reader.readLine(); LOG.info("recieved response '" + response + "'"); socket.close();/*from w ww .ja v a 2s.c om*/ return response; }
From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java
private void runTest(ServerSocket listener, ProcessBuilder launcher, StatisticsMBean stats, byte[] jobData) throws IOException, InterruptedException { Process proc = launcher.start(); //connect stdout and stderr to parent process streams if (log.isDebugEnabled()) { new PipeThread(proc.getInputStream(), System.out).start(); new PipeThread(proc.getErrorStream(), System.err).start(); } else {/* w w w . ja va2s . c om*/ NullOutput sink = new NullOutput(); new PipeThread(proc.getInputStream(), sink).start(); new PipeThread(proc.getErrorStream(), sink).start(); } //wait for the incoming connection from the child process. Socket sock = listener.accept(); try { //connection established, send the job. OutputStream os = sock.getOutputStream(); os.write(jobData); os.flush(); //read measurements back. DataInputStream dis = new DataInputStream(sock.getInputStream()); for (long measure = dis.readLong(); measure >= 0; measure = dis.readLong()) stats.add(measure); //send ack byte to tell the child proc its ok to hang up. os.write(1); os.flush(); } finally { sock.close(); } assertEquals("Child process ended successfully", 0, proc.waitFor()); }
From source file:org.jmxtrans.samples.graphite.GraphiteDataInjector.java
public void exportMetrics(TimeSeries timeSeries) throws IOException { System.out.println("Export " + timeSeries.getKey()); Socket socket = new Socket(graphiteHost, graphitePort); OutputStream outputStream = socket.getOutputStream(); if (generateDataPointsFile) { JFreeChart chart = ChartFactory.createXYLineChart("Purchase", "date", "Amount", new TimeSeriesCollection(timeSeries), PlotOrientation.VERTICAL, true, true, false); // chart.getXYPlot().setRenderer(new XYSplineRenderer(60)); File file = new File("/tmp/" + timeSeries.getKey() + ".png"); ChartUtilities.saveChartAsPNG(file, chart, 1200, 800); System.out.println("Exported " + file.getAbsolutePath()); String pickleFileName = "/tmp/" + timeSeries.getKey().toString() + ".pickle"; System.out.println("Generate " + pickleFileName); outputStream = new TeeOutputStream(outputStream, new FileOutputStream(pickleFileName)); }//from ww w .j ava 2s . c o m PyList list = new PyList(); for (int i = 0; i < timeSeries.getItemCount(); i++) { if (debug) System.out.println(new DateTime(timeSeries.getDataItem(i).getPeriod().getStart()) + "\t" + timeSeries.getDataItem(i).getValue().intValue()); String metricName = graphiteMetricPrefix + timeSeries.getKey().toString(); int time = (int) TimeUnit.SECONDS.convert(timeSeries.getDataItem(i).getPeriod().getStart().getTime(), TimeUnit.MILLISECONDS); int value = timeSeries.getDataItem(i).getValue().intValue(); list.add(new PyTuple(new PyString(metricName), new PyTuple(new PyInteger(time), new PyInteger(value)))); if (list.size() >= batchSize) { System.out.print("-"); rateLimiter.acquire(list.size()); sendDataPoints(outputStream, list); } } // send last data points if (!list.isEmpty()) { rateLimiter.acquire(list.size()); sendDataPoints(outputStream, list); } Flushables.flushQuietly(outputStream); Closeables.close(outputStream, true); Closeables.close(socket, true); System.out.println(); System.out.println("Exported " + timeSeries.getKey() + ": " + timeSeries.getItemCount() + " items"); }
From source file:com.tomcat.monitor.zabbix.ZabbixSender.java
public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host, final String key, final String value) throws IOException { final byte[] response = new byte[1024]; final long start = System.currentTimeMillis(); final int TIMEOUT = zabbixTimeout * 1000; final StringBuilder message = new StringBuilder("<req><host>"); message.append(new String(Base64.encodeBase64(host.getBytes()))); message.append("</host><key>"); message.append(new String(Base64.encodeBase64(key.getBytes()))); message.append("</key><data>"); message.append(new String(Base64.encodeBase64(value.getBytes()))); message.append("</data></req>"); if (log.isDebugEnabled()) { log.debug("sending " + message); }/*w w w. j a v a 2 s . co m*/ Socket zabbix = null; OutputStreamWriter out = null; InputStream in = null; try { zabbix = new Socket(zabbixServer, zabbixPort); zabbix.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(zabbix.getOutputStream()); out.write(message.toString()); out.flush(); in = zabbix.getInputStream(); final int read = in.read(response); if (log.isDebugEnabled()) { log.debug("received " + new String(response)); } if (read != 2 || response[0] != 'O' || response[1] != 'K') { log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'"); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbix != null) { zabbix.close(); } } log.info("send() " + (System.currentTimeMillis() - start) + " ms"); }
From source file:net.pms.network.RequestHandler.java
public RequestHandler(Socket socket) throws IOException { this.socket = socket; this.output = socket.getOutputStream(); this.br = new BufferedReader(new InputStreamReader(socket.getInputStream())); }
From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java
public void send(String server, Integer port, Long numEvents, Integer rate) { Random rnd = new Random(); BufferedReader br = null;// w w w . j a v a 2s .c om LocalDateTime st = null; try { Socket sckt = new Socket(server, port); OutputStream os = sckt.getOutputStream(); //PrintWriter sckt_out = new PrintWriter(os, true); Integer cnt = 0; st = LocalDateTime.now(); Double ns_delay = 1000000000.0 / (double) rate; long ns = ns_delay.longValue(); if (ns < 0) { ns = 0; } while (cnt < numEvents) { cnt += 1; LocalDateTime ct = LocalDateTime.now(); String dtg = ct.toString(); Double lat = 180 * rnd.nextDouble() - 90.0; Double lon = 360 * rnd.nextDouble() - 180.0; String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + "," + lat.toString() + "\"," + cnt.toString() + "\n"; final long stime = System.nanoTime(); long etime = 0; do { etime = System.nanoTime(); } while (stime + ns >= etime); if (cnt % 1000 == 0) { //System.out.println(cnt); } //sckt_out.write(line); os.write(line.getBytes()); os.flush(); } if (st != null) { LocalDateTime et = LocalDateTime.now(); Duration delta = Duration.between(st, et); Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0; send_rate = (double) numEvents / elapsed_seconds; } //sckt_out.close(); sckt.close(); os = null; //sckt_out = null; } catch (Exception e) { System.err.println(e.getMessage()); send_rate = -1.0; } finally { try { br.close(); } catch (Exception e) { // } this.send_rate = send_rate; } }