List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:net.mohatu.bloocoin.miner.SubmitListClass.java
private void submit() { for (int i = 0; i < solved.size(); i++) { try {//from w w w. j a v a 2s.c o m Socket sock = new Socket(this.url, this.port); String result = new String(); DataInputStream is = new DataInputStream(sock.getInputStream()); DataOutputStream os = null; BufferedReader in = new BufferedReader(new InputStreamReader(is)); solution = solved.get(i); hash = DigestUtils.sha512Hex(solution); String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}"; os = new DataOutputStream(sock.getOutputStream()); os.write(command.getBytes()); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } if (result.contains("\"success\": true")) { System.out.println("Result: Submitted"); MainView.updateStatusText(solution + " submitted"); Thread gc = new Thread(new CoinClass()); gc.start(); } else if (result.contains("\"success\": false")) { System.out.println("Result: Failed"); MainView.updateStatusText("Submission of " + solution + " failed, already exists!"); } is.close(); os.close(); os.flush(); sock.close(); } catch (UnknownHostException e) { MainView.updateStatusText("Submission of " + solution + " failed, connection failed!"); } catch (IOException e) { MainView.updateStatusText("Submission of " + solution + " failed, connection failed!"); } } Thread gc = new Thread(new CoinClass()); gc.start(); }
From source file:net.mohatu.bloocoin.miner.SubmitList.java
private void submit() { for (int i = 0; i < solved.size(); i++) { try {//from ww w .j a va2s. c o m Socket sock = new Socket(this.url, this.port); String result = new String(); DataInputStream is = new DataInputStream(sock.getInputStream()); DataOutputStream os = null; BufferedReader in = new BufferedReader(new InputStreamReader(is)); solution = solved.get(i); hash = DigestUtils.sha512Hex(solution); String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}"; os = new DataOutputStream(sock.getOutputStream()); os.write(command.getBytes()); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } if (result.contains("\"success\": true")) { System.out.println("Result: Submitted"); Main.updateStatusText(solution + " submitted", Color.blue); Thread gc = new Thread(new Coins()); gc.start(); } else if (result.contains("\"success\": false")) { System.out.println("Result: Failed"); Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red); } is.close(); os.close(); os.flush(); sock.close(); } catch (UnknownHostException e) { e.printStackTrace(); Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red); } catch (IOException e) { e.printStackTrace(); Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red); } } Thread gc = new Thread(new Coins()); gc.start(); }
From source file:csparql_shim.SocketStream.java
/** * start listening on a socket and forwarding to csparql * stream in defined windows to allow comparison with cqels *//*from ww w.j a va 2 s .c o m*/ @Override public void run() { ServerSocket ssock = null; Socket sock = null; try { ssock = new ServerSocket(this.port); sock = ssock.accept(); DataInputStream is = new DataInputStream(sock.getInputStream()); JSONParser parser = new JSONParser(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; int windowcount = 1; //loop for streaming in data while ((line = reader.readLine()) != null && !stop) { try { Object obj = parser.parse(line); JSONArray array = (JSONArray) obj; //stream the triple final RdfQuadruple q = new RdfQuadruple((String) array.get(0), (String) array.get(1), (String) array.get(2), System.currentTimeMillis()); this.put(q); System.out.println("triple sent at: " + System.currentTimeMillis()); } catch (ParseException pe) { System.err.println("Error when parsing input, incorrect JSON."); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:SimpleHttpServerDataProvider.java
public SimpleHttpServer(SimpleHttpServerDataProvider dataProvider, int port) { class SocketProcessor implements Runnable { private Socket s; private InputStream is; private OutputStream os; private SimpleHttpServerDataProvider dataProvider; private SocketProcessor(Socket s, SimpleHttpServerDataProvider prov) throws Throwable { this.dataProvider = prov; this.s = s; this.is = s.getInputStream(); this.os = s.getOutputStream(); }//from w w w. j a va 2 s. c o m public void run() { try { readInputHeaders(); writeResponse(""); } catch (Throwable t) { /*do nothing*/ } finally { try { s.close(); } catch (Throwable t) { /*do nothing*/ } } } private void writeResponse(String s) throws Throwable { String response = "HTTP/1.1 200 OK\r\n" + "Server: DJudge.http\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + s.length() + "\r\n" + "Connection: close\r\n\r\n"; String result = response + dataProvider.getHtmlPage(""); os.write(result.getBytes()); os.flush(); } private void readInputHeaders() throws Throwable { BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String s = br.readLine(); if (s == null || s.trim().length() == 0) { break; } } } } this.dataProvider = dataProvider; try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new SocketProcessor(s, dataProvider)).start(); } } catch (Exception e) { } catch (Throwable e) { } }
From source file:Network.CEmailHandler.java
@Override public void update(Observable o, Object arg) { Socket objSocket = (Socket) arg; int intSeq = -1; try {//from w w w . j a v a 2 s . c o m JSONParser jsonParser = new JSONParser(); JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream())); int intTempSeq = Integer.parseInt(objJSON.get("id").toString()); emailSender.getEmailsToBeSent((JSONArray) objJSON.get("messagesToBeSent")); emailSender.dispatchEmail(); intSeq = intTempSeq; } catch (IOException | ParseException | NumberFormatException ex) { System.out.println(ex); } finally { try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()), StandardCharsets.US_ASCII.name())) { objWriter.write(intSeq + ""); objWriter.flush(); } catch (IOException ex) { System.out.println(ex); } } }
From source file:com.lion328.xenonlauncher.proxy.HttpDataHandler.java
@Override public boolean process(Socket client, Socket server) throws Exception { InputStream clientIn = client.getInputStream(); clientIn.mark(65536);// w ww . j av a 2 s. co m try { DefaultBHttpServerConnection httpClient = new DefaultBHttpServerConnection(8192); httpClient.bind(client); httpClient.setSocketTimeout(timeout); DefaultBHttpClientConnection httpServer = new DefaultBHttpClientConnection(8192); httpServer.bind(server); HttpCoreContext context = HttpCoreContext.create(); context.setAttribute("client.socket", client); context.setAttribute("server.socket", server); HttpEntityEnclosingRequest request; do { HttpRequest rawRequest = httpClient.receiveRequestHeader(); if (rawRequest instanceof HttpEntityEnclosingRequest) { request = (HttpEntityEnclosingRequest) rawRequest; } else { request = new BasicHttpEntityEnclosingRequest(rawRequest.getRequestLine()); request.setHeaders(rawRequest.getAllHeaders()); } httpClient.receiveRequestEntity(request); HttpResponse response = new BasicHttpResponse( new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); boolean sent = false; for (Map.Entry<Integer, HttpRequestHandler> entry : handlers.entrySet()) { entry.getValue().handle(request, response, context); if (context.getAttribute("response.set") instanceof HttpResponse) { response = (HttpResponse) context.getAttribute("response.set"); } if (context.getAttribute("pipeline.end") == Boolean.TRUE) { break; } if (context.getAttribute("response.need-original") == Boolean.TRUE && !sent) { httpServer.sendRequestHeader(request); httpServer.sendRequestEntity(request); response = httpServer.receiveResponseHeader(); httpServer.receiveResponseEntity(response); entry.getValue().handle(request, response, context); context.removeAttribute("response.need-original"); context.setAttribute("request.sent", true); sent = true; } } if (context.getAttribute("response.sent") != Boolean.TRUE) { httpClient.sendResponseHeader(response); if (response.getEntity() != null) { httpClient.sendResponseEntity(response); } } } while (request.getFirstHeader("Connection").getValue().equals("keep-alive")); return true; } catch (ProtocolException e) { clientIn.reset(); return false; } catch (ConnectionClosedException e) { return true; } }
From source file:cqels_shim.SocketStream.java
/** * start listening on the socket and forwarding to cqels *//*from w w w . ja v a 2 s . c o m*/ public void run() { ServerSocket ssock = null; Socket sock = null; try { ssock = new ServerSocket(this.port); sock = ssock.accept(); DataInputStream is = new DataInputStream(sock.getInputStream()); JSONParser parser = new JSONParser(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null && !stop) { try { Object obj = parser.parse(line); JSONArray array = (JSONArray) obj; //stream the triple stream(n((String) array.get(0)), n((String) array.get(1)), n((String) array.get(2))); } catch (ParseException pe) { System.err.println("Error when parsing input, incorrect JSON."); } if (sleep > 0) { try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } }
From source file:Network.CSMSHandler.java
@Override public void update(Observable o, Object arg) { Socket objSocket = (Socket) arg; int intSeq = -1; try {// w w w . j a v a2 s . co m JSONParser jsonParser = new JSONParser(); JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream())); int intTempSeq = Integer.parseInt(objJSON.get("id").toString()); for (CSMS objSMS : CSMSManager.loadFromJson((JSONArray) objJSON.get("sms"))) { CSMSFactory.getSMSSender().sendSMS(objSMS); } intSeq = intTempSeq; } catch (Exception ex) { System.out.println(ex); } finally { try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()), StandardCharsets.US_ASCII.name())) { objWriter.write(intSeq + ""); objWriter.flush(); } catch (IOException ex) { System.out.println(ex); } } }
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 {// w w w . j a v a 2 s . 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:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java
private String getResponse(Socket socket) { try {/*from www. j a va2 s .c o m*/ StringWriter writer = new StringWriter(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (reader != null) { String line; while (!StringUtils.isEmpty(line = reader.readLine())) { writer.append(line).append("\r\n"); } } return writer.toString(); } catch (IOException e) { return null; } }