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:client.communication.SocketClient.java

/**
 * Envia a mensagem para o servidor e retorna a resposta
 * //from   www.  j av a  2s .c  o m
 * @param message
 * @return 
 */
public String sendMessage(String message) {
    Socket socket = null;

    PrintStream stream = null;

    try {
        socket = new Socket(serverAddress, serverPort);

        stream = new PrintStream(socket.getOutputStream());

        // Envia requisiao
        stream.println(message);

        // L resposta
        socket.getInputStream().read(response);
    } catch (IOException e) {
        System.out.println("Problem connecting server!");
    } finally {
        try {
            // Fecha stream
            if (stream != null)
                stream.close();

            if (socket != null)
                socket.close();
        } catch (IOException e) {
            System.err.println("Problem closing socket: " + e.getMessage());
        }
    }

    // Decodifica resposta em base 64
    String _reply = new String(Base64.decodeBase64(response));

    // Remove o espao nas extremidades da string de resposta
    return _reply.trim();
}

From source file:de.iew.imageupload.actions.UploadImageAction.java

public void actionPerformed(ActionEvent ev) {
    try {// ww  w  . j a  va  2  s .  c  om
        Socket socket = new Socket("squeeze", 8124);

        FileInputStream fin = new FileInputStream(this.fileToUpload);
        OutputStream out = socket.getOutputStream();

        IOUtils.copy(fin, out);

        out.flush();
        fin.close();
        out.close();

        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.atunes.kernel.modules.proxy.Proxy.java

public Proxy(Type type, String url, int port, String user, String password)
        throws UnknownHostException, IOException {
    super(type, new Socket(url, port).getRemoteSocketAddress());
    this.url = url;
    this.port = port;
    this.user = user;
    this.password = password;
}

From source file:epn.edu.ec.bibliotecadigital.cliente.Client.java

@Override
public void run() {
    try {//from w w w .  j a  v  a2 s .  c  o  m
        clientSocketBalancer = new Socket(InetAddress.getByName(serverIP), portBalancer);
        DataInputStream dataInBalancer = new DataInputStream(clientSocketBalancer.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocketBalancer.getOutputStream());
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        String ipServer = dataInBalancer.readUTF();
        int portServer = dataInBalancer.readInt();
        clientSocketBalancer.close();
        Socket clientSocket = new Socket(ipServer, portServer);
        dataOut = new DataOutputStream(clientSocket.getOutputStream());
        dataOut.writeUTF(accion);
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        InputStream in;
        DataInputStream dataIn;
        switch (accion) {
        case "bajar":

            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF((String) params[1]);
            dataIn = new DataInputStream(clientSocket.getInputStream());
            boolean encontrado = dataIn.readBoolean();
            if (!encontrado) {
                System.out.println("Libro con el cdigo: " + params[1] + " no encontrado");
                break;
            }
            String fileName = dataIn.readUTF();
            System.out.println(
                    "Descargando libro " + fileName + " con cdigo " + params[1] + " en la carpeta Donwloads");
            String home = System.getProperty("user.home");

            in = clientSocket.getInputStream();
            try {
                FileOutputStream out = new FileOutputStream(new File(home + "\\Downloads\\" + fileName));
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "subir":
            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF(((File) params[1]).getName());
            OutputStream out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                in = new FileInputStream((File) params[1]);

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "obtenerLista":
            ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Libros disponibles: \n");
            List<Libro> libros = (List<Libro>) inFromClient.readObject();
            System.out.println("\tCdigo\tNommbre\n");
            for (Libro lbr : libros) {
                System.out.println("\t" + lbr.getCodigolibro() + "\t" + lbr.getNombre());
            }
            inFromClient.close();
            break;
        case "verificar":

            break;
        }
        dataOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManagerTest.java

@Test
public void testChooseClientAliasNotfound() throws Exception {
    final X509KeyManager m = new CertificateStoreX509KeyManager(new DisabledCertificateStore()).init();
    assertNull(m.chooseClientAlias(new String[] { "RSA", "DSA" },
            new Principal[] { new BasicUserPrincipal("user") }, new Socket("test.cyberduck.ch", 443)));
}

From source file:com.liferay.nativity.control.unix.UnixNativityControlBaseImpl.java

@Override
public boolean connect() {
    try {//from  ww w.ja  va 2 s.  c o  m
        _commandSocket = new Socket("127.0.0.1", _commandSocketPort);

        _commandBufferedReader = new BufferedReader(
                new InputStreamReader(_commandSocket.getInputStream(), "UTF-8"));

        _commandOutputStream = new DataOutputStream(_commandSocket.getOutputStream());

        _callbackSocket = new Socket("127.0.0.1", _callbackSocketPort);

        _callbackBufferedReader = new BufferedReader(
                new InputStreamReader(_callbackSocket.getInputStream(), "UTF-8"));

        _callbackOutputStream = new DataOutputStream(_callbackSocket.getOutputStream());

        _callbackThread = new ReadThread(this);

        _callbackThread.start();

        _connected = true;

        if (_logger.isDebugEnabled()) {
            _logger.debug("Successfully connected to command socket: {}", _commandSocketPort);

            _logger.debug("Successfully connected to service socket: {}", _callbackSocketPort);
        }

        return true;
    } catch (IOException e) {
        _logger.error(e.getMessage());
    }

    _connected = false;

    return false;
}

From source file:bankingclient.DNFrame.java

public DNFrame(MainFrame vmain) {

    initComponents();/*from w ww.j  a v a 2 s  . c o m*/

    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField_cmt.setText("");
    this.jTextField_sdt.setText("");

    this.main = vmain;
    noAcc = new NewOrOldAccFrame(this);
    this.setVisible(false);
    jL_sdt.setVisible(false);
    jL_cmtnd.setVisible(false);
    jTextField_cmt.setVisible(false);
    jTextField_sdt.setVisible(false);

    jBt_dn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (!jCheck_qmk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(2);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField2.getText());
                    dout.flush();
                    while (true) {
                        break;
                    }
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());

                    } else {
                        JOptionPane.showMessageDialog(new JFrame(),
                                "Tn ?ang Nhp Khng Tn Ti, hoac mat khau sai");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Mng....");
                }
            } else if ((!jTextField_cmt.getText().equals("")) && (!jTextField_sdt.getText().equals(""))
                    && (NumberUtils.isNumber(jTextField_cmt.getText()))
                    && (NumberUtils.isNumber(jTextField_sdt.getText()))) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(9);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField_sdt.getText() + "\n"
                            + jTextField_cmt.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());
                    } else {
                        JOptionPane.showMessageDialog(new JFrame(), "Khong dang nhap duoc, thong tin sai");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Can dien day du thong tin va dung mau");
            }
        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DNFrame.this.setVisible(false);
        }
    });
    jCheck_qmk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jCheck_qmk.isSelected()) {
                jL_sdt.setVisible(true);
                jL_cmtnd.setVisible(true);
                jTextField_cmt.setVisible(true);
                jTextField_sdt.setVisible(true);
            } else {
                jL_sdt.setVisible(false);
                jL_cmtnd.setVisible(false);
                jTextField_cmt.setVisible(false);
                jTextField_sdt.setVisible(false);
            }
        }
    });
}

From source file:com.citruspay.enquiry.gateway.AXISGatewayConnector.java

public String connect(String vpcHost, String queryParameters, EnquiryRequest request) {

    boolean useSSL = false;
    String fileName = "";

    // determine if SSL encryption is being used
    if (vpcHost.substring(0, 8).equalsIgnoreCase("HTTPS://")) {
        useSSL = true;//  ww w.  j a  va  2 s .com
        // remove 'HTTPS://' from host URL
        vpcHost = vpcHost.substring(8);
        // get the filename from the last section of vpc_URL
        fileName = vpcHost.substring(vpcHost.lastIndexOf("/"));
        // get the IP address of the VPC machine
        vpcHost = vpcHost.substring(0, vpcHost.lastIndexOf("/"));
    }

    try {
        Socket socket = null;
        if (useSSL) {
            socket = getSocket(vpcHost, vpc_Port);
            // use next block of code if NOT using SSL encryption
        } else {
            socket = new Socket(vpcHost, vpc_Port);
        }
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        os.write(prepareCompleteQueryString(fileName, queryParameters).getBytes());
        String res = new String(readAll(is));

        // check if a successful connection
        if (res.indexOf("200") < 0) {
            throw new IOException("Connection Refused - " + res);
        }

        if (res.indexOf("404 Not Found") > 0) {
            throw new IOException("File Not Found Error - " + res);
        }

        int resIndex = res.indexOf("\r\n\r\n");
        String body = res.substring(resIndex + 4, res.length());
        return body;

    } catch (IOException ioe) {
    }
    return StringUtils.EMPTY;
}

From source file:com.esri.geoevent.test.performance.tcp.TcpEventProducer.java

@Override
public synchronized void init(Config config) throws TestException {
    super.init(config);
    try {/*from  ww  w  . j  a  v a  2 s.c  om*/
        host = config.getPropertyValue("hosts", "localhost");
        port = Integer.parseInt(config.getPropertyValue("port", "5565"));
        socket = new Socket(host, port);
        os = socket.getOutputStream();
    } catch (Throwable error) {
        throw new TestException(
                ImplMessages.getMessage("INIT_FAILURE", getClass().getName(), error.getMessage()), error);
    }
}

From source file:ch.aonyx.broker.ib.api.NeoIbApiClient.java

public void connect(final ConnectionParameters connectionParameters, final ConnectionCallback callback) {
    Validate.notNull(connectionParameters);
    Validate.notNull(callback);//ww  w  .j a  va  2 s.  c o m
    try {
        socket = new Socket(connectionParameters.getHost(), connectionParameters.getPort());
        callback.onSuccess(new SocketSession(socket, connectionParameters.getClientId(), clientCallback));
    } catch (final UnknownHostException e) {
        LOGGER.error("", e);
        callback.onFailure(
                new ConnectionException(ClientMessageCode.CONNECTION_ERROR, "Unknown host " + e.getMessage()));
    } catch (final IOException e) {
        LOGGER.error("", e);
        callback.onFailure(new ConnectionException(ClientMessageCode.CONNECTION_FAILURE, e.getMessage()));
    }
}