List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:guardar.en.base.de.datos.MainServidor.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException { Mongo mongo = new Mongo("localhost", 27017); // nombre de la base de datos DB database = mongo.getDB("paginas"); // coleccion de la db DBCollection collection = database.getCollection("indice"); DBCollection collection_textos = database.getCollection("tabla"); ArrayList<String> lista_textos = new ArrayList(); try {//from ww w. j a va 2s .com ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue. while (true) { String aux = new String(); lista_textos.clear(); Socket clienteNuevo = servidor.accept();// Si llega se acepta. // Queda en pausa otra vez hasta que un objeto llegue. ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream()); JSONObject request = (JSONObject) entrada.readObject(); String b = (String) request.get("id"); //hacer una query a la base de datos con la palabra que se quiere obtener BasicDBObject query = new BasicDBObject("palabra", b); DBCursor cursor = collection.find(query); ArrayList<DocumentosDB> lista_doc = new ArrayList<>(); // de la query tomo el campo documentos y los agrego a una lista try { while (cursor.hasNext()) { //System.out.println(cursor.next()); BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos"); // en el for voy tomando uno por uno los elementos en el campo documentos for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) { BasicDBObject dbo = (BasicDBObject) it.next(); //DOC tiene id y frecuencia DocumentosDB doc = new DocumentosDB(); doc.makefn2(dbo); //int id = (int)doc.getId_documento(); //int f = (int)doc.getFrecuencia(); lista_doc.add(doc); //******************************************* //******************************************** //QUERY A LA COLECCION DE TEXTOS /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query DBCursor cursor_textos = collection_textos.find(query_textos); try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = (String) obj.get("titulo"); titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto; aux = texto_final; lista_textos.add(texto_final); } } finally { cursor_textos.close(); }*/ //System.out.println(doc.getId_documento()); //System.out.println(doc.getFrecuencia()); } // end for } //end while query } finally { cursor.close(); } // ordeno la lista de menor a mayor Collections.sort(lista_doc, new Comparator<DocumentosDB>() { @Override public int compare(DocumentosDB o1, DocumentosDB o2) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. return o1.getFrecuencia().compareTo(o2.getFrecuencia()); } }); int tam = lista_doc.size() - 1; for (int j = tam; j >= 0; j--) { BasicDBObject query_textos = new BasicDBObject("id", (int) lista_doc.get(j).getId_documento().intValue());//query DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = "*******************************"; titulo += (String) obj.get("titulo"); int f = (int) lista_doc.get(j).getFrecuencia().intValue(); String strinf = Integer.toString(f); titulo += "******************************* frecuencia:" + strinf; titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto + "\n\n"; aux = aux + texto_final; //lista_textos.add(texto_final); } } finally { cursor_textos.close(); } } //actualizar el cache try { Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server JSONObject actualizacion_cache = new JSONObject(); actualizacion_cache.put("actualizacion", 1); actualizacion_cache.put("busqueda", b); actualizacion_cache.put("respuesta", aux); mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor } catch (Exception ex) { } //RESPONDER DESDE EL SERVIDORIndex al FRONT ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj resp.writeObject(aux); System.out.println("msj enviado desde el servidor"); } } catch (IOException ex) { Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.splout.db.dnode.TCPStreamer.java
/** * This main method can be used for testing the TCP interface directly to a * local DNode. Will ask for protocol input from Stdin and print output to * Stdout// w ww . j a v a 2s . c om */ public static void main(String[] args) throws UnknownHostException, IOException, SerializationException { SploutConfiguration config = SploutConfiguration.get(); Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT)); DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); DataOutputStream outToServer = new DataOutputStream( new BufferedOutputStream(clientSocket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter tablespace: "); String tablespace = reader.readLine(); System.out.println("Enter version number: "); long versionNumber = Long.parseLong(reader.readLine()); System.out.println("Enter partition: "); int partition = Integer.parseInt(reader.readLine()); System.out.println("Enter query: "); String query = reader.readLine(); outToServer.writeUTF(tablespace); outToServer.writeLong(versionNumber); outToServer.writeInt(partition); outToServer.writeUTF(query); outToServer.flush(); byte[] buffer = new byte[0]; boolean read; do { read = false; int nBytes = inFromServer.readInt(); if (nBytes > 0) { buffer = new byte[nBytes]; int inRead = inFromServer.read(buffer); if (inRead > 0) { Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class); read = true; System.out.println(Arrays.toString(res)); } } } while (read); clientSocket.close(); }
From source file:Main.java
public static void whois(String query, String server) throws IOException { Socket sock = new Socket(server, 43); int c = 0;// ww w .ja va2s . c o m OutputStream os = sock.getOutputStream(); InputStream is = sock.getInputStream(); query += "\r\n"; os.write(query.getBytes("iso8859_1")); while (c != -1) { c = is.read(); if (c != -1) System.out.println((char) c); } }
From source file:Main.java
public static String getSocketLocalIpAddress() { String ipAddress = ""; Socket socket;/* ww w .j a va 2 s . c o m*/ try { socket = new Socket("www.google.com", 80); ipAddress = socket.getLocalAddress().toString(); ipAddress = ipAddress.replace("/", ""); Log.i(TAG, "IP by socket: " + ipAddress); socket.close(); return ipAddress; } catch (Exception e) { Log.i(TAG, e.getMessage()); } return ipAddress; }
From source file:Main.java
/** * Performs execution of the shell command on remote host. * @param host ip address or name of the host. * @param port telnet port/* w ww. ja v a 2 s . c o m*/ * @param command shell command to be executed. * @return true if success, false on error. */ public static final boolean executeRemotely(String host, int port, String command) { Socket socket = null; OutputStream os = null; try { socket = new Socket(host, port); os = socket.getOutputStream(); os.write(command.getBytes()); os.flush(); return true; } catch (UnknownHostException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null && !socket.isClosed()) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:Main.java
public static void sendStopSignal(int port) { try {// ww w . j a v a 2 s . c om Socket s = new Socket(InetAddress.getByName("127.0.0.1"), port); OutputStream out = s.getOutputStream(); System.err.println("sending server stop request"); out.write(("\r\n").getBytes()); out.flush(); s.close(); } catch (Exception e) { // can happen when called twice by jvm shutdown hook System.err.println("stop monitor thread has terminated"); } }
From source file:Main.java
/** * Creates a new socket that can be configured to serve as a transparent proxy to a * remote machine. This can be achieved by calling configureSocket() * * @return a socket that can be configured to link to remote machine * @throws IOException// w ww.jav a 2 s . c om */ public static Socket createSocket() throws IOException { return new Socket(ADB_HOST, ADB_PORT); }
From source file:MainClass.java
public void run() { try {//from ww w. j av a2 s . co m Socket socket = new Socket("127.0.0.1", 2000); DataInputStream in = new DataInputStream(socket.getInputStream()); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); while (true) { System.out.print("Enter response: "); String response = console.readLine(); out.writeUTF(response); String message = in.readUTF(); System.out.println(message); } } catch (IOException e) { e.printStackTrace(); } }
From source file:Finger.java
public String finger(String host, String users) throws IOException, SocketException { String outstring = ""; int c = 0;//from w w w. j ava 2s .c o m Socket sock = new Socket(host, 79); OutputStream os = sock.getOutputStream(); InputStream is = sock.getInputStream(); users = users + "\r\n"; os.write(users.getBytes("iso8859_1")); try { while (c != -1) { c = is.read(); if (c != -1) outstring += (char) c; } } catch (IOException e) { } return outstring; }
From source file:org.cloudfoundry.identity.uaa.api.client.test.AbstractOperationTest.java
protected static void init() throws Exception { try {// w ww . j a v a 2 s. c om Socket test = new Socket("localhost", 8080); uaaRunning = true; test.close(); } catch (IOException e) { System.err.println("UAA is not running, skip these tests"); uaaRunning = false; return; } finally { String baseUrl = "http://localhost:8080/uaa"; ClientCredentialsResourceDetails credentials = new ClientCredentialsResourceDetails(); credentials.setAccessTokenUri(baseUrl + "/oauth/token"); // credentials.setAuthenticationScheme(AuthenticationScheme.header); credentials.setClientAuthenticationScheme(AuthenticationScheme.header); credentials.setClientId("admin"); credentials.setClientSecret("adminsecret"); connection = UaaConnectionFactory.getConnection(new URL(baseUrl), credentials); } }