Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

In this page you can find the example usage for java.net Socket Socket.

Prototype

public Socket(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:com.cyberway.issue.crawler.fetcher.HeritrixProtocolSocketFactory.java

/**
 * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
 *//*w  w w .  j ava  2  s .  co m*/
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return new Socket(host, port);
}

From source file:com.smartmarmot.orabbix.Sender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    //message.append(Base64.encode(key));
    message.append(base64Encode(key));//from www.ja  va 2 s .  c om
    message.append(middle);
    //message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    if (log.isDebugEnabled()) {
        SmartLogger.logThis(Level.DEBUG, "sending " + message);
    }

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    Enumeration<String> serverlist = zabbixServers.keys();

    while (serverlist.hasMoreElements()) {
        String zabbixServer = serverlist.nextElement();
        try {
            zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue());
            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()) {
                SmartLogger.logThis(Level.DEBUG, "received " + new String(response));
            }
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                SmartLogger.logThis(Level.WARN,
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + "  on port "
                    + zabbixServers.get(zabbixServer));
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

From source file:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java

private void actualizarLibrosEnServidores(String fileName) {
    try {//w w w. j a  v a  2s. c  o m
        Socket socket = new Socket("192.168.100.14", 8888);
        DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream());
        dataOut.writeUTF("actualizar");
        dataOut.writeUTF("servidor");
        dataOut.writeUTF(fileName);
        OutputStream out = socket.getOutputStream();
        try {
            byte[] bytes = new byte[64 * 1024];
            InputStream in = new FileInputStream("C:\\Computacion Distribuida\\" + fileName);

            int count;
            while ((count = in.read(bytes)) > 0) {
                out.write(bytes, 0, count);
            }
            in.close();
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (IOException ex) {
        Logger.getLogger(ServerRunnable.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test robustness./*from ww w. j a v  a  2s . com*/
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingArgument() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(29, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

public String openPassiveMode() throws IOException {
    sendCommand("PASV");
    String response = getResponse();
    int parentStart = response.lastIndexOf('(');
    int parentEnd = response.lastIndexOf(')');

    String pasv = response.substring(parentStart + 1, parentEnd);
    StringTokenizer st = new StringTokenizer(pasv, ",");
    int[] iPs = new int[8];
    for (int i = 0; st.hasMoreTokens(); i++) {
        iPs[i] = Integer.valueOf(st.nextToken());
    }/*from  w  w  w.  j  a v a2  s  .com*/
    int port = (iPs[4] << FtpConstants.BYTE_LENGTH) + iPs[5];

    resetDataSockets();
    passiveModeSocket = new Socket(server, port);
    return response;
}

From source file:com.ctsim.dmi.App.java

private void initCommunication() {
    System.out.println("try to connecting");

    try {/*from  w  w w . j av a  2s.c om*/
        socket = new Socket("192.168.1.10", 2510);

        if (socket.isConnected()) {
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println("SESSION=DMI");
            out.flush();
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
    } catch (IOException ex) {
        System.out.println("connection fail");
    }
}

From source file:io.s4.client.Driver.java

/**
 * Initialize the driver.//from  w ww  .ja v a2  s  . c om
 * 
 * Handshake with adapter to receive a unique id, and verify that the driver
 * is compatible with the protocol used by the adapter. This does not
 * actually establish a connection for sending and receiving events.
 * 
 * @see #connect(ReadMode, WriteMode)
 * 
 * @return true if and only if the adapter issued a valid ID to this client,
 *         and the protocol is found to be compatible.
 * @throws IOException
 *             if the underlying TCP/IP socket throws an exception.
 */
public boolean init() throws IOException {
    if (state.isInitialized())
        return true;

    try {
        sock = new Socket(hostname, port);

        ByteArrayIOChannel io = new ByteArrayIOChannel(sock);

        io.send(emptyBytes);

        byte[] b = io.recv();

        if (b == null || b.length == 0) {
            if (debug) {
                System.err.println("Empty response during initialization.");
            }
            return false;
        }

        JSONObject json = new JSONObject(new String(b));

        this.uuid = json.getString("uuid");

        JSONObject proto = json.getJSONObject("protocol");

        if (!isCompatible(proto)) {
            if (debug) {
                System.err.println("Driver not compatible with adapter protocol: " + proto);
            }
            return false;
        }

        state = State.Initialized;

        return true;

    } catch (JSONException e) {
        if (debug) {
            System.err.println("malformed JSON in initialization response. " + e);
        }
        e.printStackTrace();
        return false;

    } finally {
        sock.close();
    }
}

From source file:any.Linker.java

public void connect(String name, String host, int port) {
    try {//  w w w. ja v a 2  s.com
        Socket s;
        s = new Socket(host, port);

        Connection conn = new Connection(name, this, s);

        namedCon.put(name, conn);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}