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.bmwcarit.barefoot.matcher.ServerTest.java

private void sendRequest(InetAddress host, int port, JSONArray samples)
        throws InterruptedException, IOException, JSONException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;// w  w w  .  j av  a2  s  .co m

    while (client == null || !client.isConnected()) {
        try {
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                client.close();
                throw new IOException(e.getMessage());
            } else {
                trials -= 1;
            }
        }
    }

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(samples.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    MatcherKState state = new MatcherKState(new JSONObject(response),
            new MatcherFactory(ServerControl.getServer().getMap()));

    OutputFormatter output = new GeoJSONOutputFormatter();
    PrintWriter out = new PrintWriter(ServerTest.class.getResource("").getPath() + "ServerTest-matching.json");
    out.println(output.format(null, state));
    out.close();

    assertEquals(samples.length(), state.sequence().size());
}

From source file:com.fuzhepan.arpc.client.ProxyHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    log.debug("invoke was called!");

    if (method.getName().equals("toString")) {
        return "toString method was called";
    }/*from  ww  w.  j a  va 2 s.  c o  m*/

    RpcContext rpcContext = new RpcContext(interfaceName, method.getName(), method.getParameterTypes(), args);

    //get service info and load balance
    List<HostPortPair> serviceList = RpcConfig.getServiceList(serviceName);
    if (serviceList == null || serviceList.size() == 0)
        throw new ClassNotFoundException("not find service : " + serviceName);
    int index = requestCount.get() % serviceList.size();
    if (requestCount.get() > 100)
        requestCount.set(0);
    else
        requestCount.getAndIncrement();
    HostPortPair hostPort = serviceList.get(index);

    Socket socket = new Socket(hostPort.host, hostPort.port);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
    objectOutputStream.writeObject(rpcContext);
    objectOutputStream.flush();

    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
    Object response = objectInputStream.readObject();

    objectInputStream.close();
    objectOutputStream.close();
    socket.close();

    Class methodReturnType = method.getReturnType();
    return methodReturnType.cast(response);
}

From source file:net.mohatu.bloocoin.miner.SubmitListClass.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from  ww w.j av  a2 s  . com*/
            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:com.lyonsdensoftware.vanitymirror.PythonConnectionThread.java

@Override
public void run() {
    // Try connecting to the master server
    try {//from  ww  w .jav a 2 s .c o  m

        // Create a socket to connect to the server
        this.socket = new Socket(this.mainWindow.getConfigFile().getHostname(),
                this.mainWindow.getConfigFile().getPort());

        // Note it in the log
        log.info("LOG", "Connect to MasterServer at IP: " + socket.getInetAddress().getHostAddress()
                + " on PORT: " + socket.getPort());

        connectedToServer = true;

        // Create an input stream to receive data from the server
        mainWindow.setFromServer(new DataInputStream(socket.getInputStream()));

        // Create an output stream to send data to the server
        mainWindow.setToServer(new DataOutputStream(socket.getOutputStream()));

        // Main Loop
        while (runThread) {

            // Check for data from the server
            BufferedReader in = new BufferedReader(new InputStreamReader(mainWindow.getFromServer()));

            if (in.ready()) {
                // Convert in data to json
                Gson gson = new Gson();

                JSONObject json = new JSONObject(gson.fromJson(in.readLine(), JSONObject.class));

                if (json.keys().hasNext()) {
                    // handle the data
                    handleDataFromServer(json);
                } else {
                    System.out.println(json.toString());
                }
            }
        }

        // Loop not running now so close connection
        socket.close();
        mainWindow.getFromServer().close();
        mainWindow.getToServer().close();
    } catch (IOException ex) {
        log.error("ERROR", ex.toString());
    }
}

From source file:bankingclient.ChonThaoTacFrame.java

public ChonThaoTacFrame(NewOrOldAccFrame acc) {
    initComponents();//from   w ww  . ja  v a2s .c o m
    jTextField1.setText("");

    jLabel4.setVisible(false);
    jComboBox2.setVisible(false);
    jLabel2.setVisible(false);
    jLabel3.setVisible(false);
    jTextField1.setVisible(false);
    jBt_xn1.setVisible(false);
    jBt_xn2.setVisible(false);

    this.accList = null;
    this.cusList = null;
    this.noAcc = acc;
    this.tt = new Thong_Tin_TK(this);
    this.setVisible(false);

    jBt_xn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jTextField1.getText()) && (Long.parseLong(jTextField1.getText()) > 0)) {
                long currentMoney = 0;
                try {
                    Socket client = new Socket("113.22.46.207", 6013);

                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(8);
                    dout.writeUTF((String) jComboBox1.getSelectedItem());
                    dout.flush();

                    DataInputStream din = new DataInputStream(client.getInputStream());
                    Scanner lineScanner = new Scanner(din.readUTF());
                    currentMoney = Long.parseLong(lineScanner.nextLine());
                    System.out.println(currentMoney);

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane,
                            "Li kt ni mng,bn cn kim tra kt ni");
                }

                if (jCheck_gt.isSelected()) {
                    try {
                        Socket client = new Socket("113.22.46.207", 6013);
                        DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                        dout.writeByte(5);
                        dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText()
                                + "\n" + (noAcc.getCustomer()));
                        dout.flush();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy ra....");
                    }
                    JOptionPane.showMessageDialog(rootPane, "Gi Ti?n Thnh Cng...");
                }

                if (jCheck_rt.isSelected()) {
                    if ((Long.parseLong(jTextField1.getText()) <= currentMoney)) {
                        try {
                            Socket client = new Socket("113.22.46.207", 6013);
                            DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                            dout.writeByte(6);
                            dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText()
                                    + "\n" + (noAcc.getCustomer()));
                            dout.flush();

                        } catch (Exception ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy Ra.....");
                        }
                        JOptionPane.showMessageDialog(rootPane, "Rt Ti?n Thnh Cng ...");
                    } else {
                        System.out.println("Khng  Ti?n Trong ti khon.." + currentMoney);
                        JOptionPane.showMessageDialog(null, "Ti Khon Khng ? ? Rt ...");
                    }
                }

                noAcc.setVisible(true);
                ChonThaoTacFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane,
                        "Cn Nhp Li S Ti?n Cn Gi Hoc Rt..");
            }

        }
    });

    jBt_tt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tt.setTk((String) jComboBox1.getSelectedItem());
            tt.hienTenTk();
            long currentMoney = 0;
            try {
                Socket client = new Socket("113.22.46.207", 6013);

                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(8);
                dout.writeUTF((String) jComboBox1.getSelectedItem());
                dout.flush();

                DataInputStream din = new DataInputStream(client.getInputStream());
                Scanner lineScanner = new Scanner(din.readUTF());
                currentMoney = Long.parseLong(lineScanner.nextLine());
                //                    System.out.println(currentMoney);

            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(rootPane,
                        "Li kt ni mng,bn cn kim tra kt ni");
            }
            tt.hienSoDu(((Long) currentMoney).toString());
            tt.setVisible(true);
            try {
                Socket client = new Socket("113.22.46.207", 6013);

                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(10);
                dout.writeUTF((String) jComboBox1.getSelectedItem());
                dout.flush();

                DataInputStream din = new DataInputStream(client.getInputStream());
                Scanner cusScanner = new Scanner(din.readUTF());
                while (cusScanner.hasNextLine()) {
                    tt.addCus(cusScanner.nextLine());
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            tt.hienChuTaiKhoan();
            try {
                Socket client = new Socket("113.22.46.207", 6013);
                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(12);
                dout.writeUTF((String) jComboBox1.getSelectedItem());
                dout.flush();

                DataInputStream din = new DataInputStream(client.getInputStream());
                Scanner dateScanner = new Scanner(din.readUTF());
                int day = Integer.parseInt(dateScanner.nextLine());
                int month = Integer.parseInt(dateScanner.nextLine());
                int year = Integer.parseInt(dateScanner.nextLine());
                String date = (day + "-" + month + "-" + year);
                tt.hienNgayLapTaiKhoan(date);
                while (dateScanner.hasNextLine()) {
                    //                        System.out.println("aaa");
                    tt.addGiaoDich(dateScanner.nextLine());
                }
                tt.hienGiaoDich();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            ChonThaoTacFrame.this.setVisible(false);
        }
    });

    jBt_xn2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_tctk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(7);
                    dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n"
                            + (String) jComboBox2.getSelectedItem());
                    dout.flush();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane,
                            "C Li Kt Ni Xy Ra\n Thm Ch Tht Bi...");
                }
                JOptionPane.showMessageDialog(rootPane, "Thm Ch Ti Khon Thnh Cng..");
            } else {
                System.out.println("nothing to do...");
            }
        }
    });

    jBt_xtk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Socket client = new Socket("113.22.46.207", 6013);
                DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                dout.writeByte(11);
                String sent = (String) (jComboBox1.getSelectedItem()) + "\n" + noAcc.getCustomer();
                dout.writeUTF(sent);
                dout.flush();
                DataInputStream din = new DataInputStream(client.getInputStream());
                byte check = din.readByte();
                if (check == 1) {
                    JOptionPane.showMessageDialog(rootPane, "xoa tai khoan thanh cong");
                } else {
                    JOptionPane.showMessageDialog(rootPane,
                            "<html>xoa tai khoan <b>khong</b> thanh cong <br> chi chu chinh moi co the xoa tai khoan</html>");
                }

            } catch (Exception ee) {
                ee.printStackTrace();
                JOptionPane.showMessageDialog(rootPane, "Li Kt Ni ,Vui Lng Kim Tra Li..");
            }
        }
    });

    /*dont touch*/
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            ChonThaoTacFrame.this.setVisible(false);
        }
    });
    /*dont touch*/

    jComboBox1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });

    jComboBox2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });

    /*dont touch jcheckbox*/
    jCheck_tctk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_tctk.isSelected()) {
                jLabel4.setVisible(true);
                jComboBox2.setVisible(true);
                jBt_xn2.setVisible(true);
            } else {
                jLabel4.setVisible(false);
                jComboBox2.setVisible(false);
                jBt_xn2.setVisible(false);
            }
        }
    });
    jCheck_gt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_gt.isSelected()) {
                if (jCheck_rt.isSelected()) {
                    jCheck_rt.setSelected(false);
                }
                jLabel2.setVisible(true);
                jLabel3.setVisible(true);
                jTextField1.setVisible(true);
                jBt_xn1.setVisible(true);
            } else {
                jLabel2.setVisible(false);
                jLabel3.setVisible(false);
                jTextField1.setVisible(false);
                jBt_xn1.setVisible(false);
            }
        }
    });
    jCheck_rt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jCheck_rt.isSelected()) {
                if (jCheck_gt.isSelected()) {
                    jCheck_gt.setSelected(false);
                }
                jLabel2.setVisible(true);
                jLabel3.setVisible(true);
                jTextField1.setVisible(true);
                jBt_xn1.setVisible(true);
            } else {
                jLabel2.setVisible(false);
                jLabel3.setVisible(false);
                jTextField1.setVisible(false);
                jBt_xn1.setVisible(false);
            }
        }
    });
    /*dont touch jcheckbox*/
}

From source file:it.holiday69.phpwebserver.httpd.fastcgi.impl.PoolFactory.java

/**
 * builds a new socket using one of the descriptors.
 *///from  w  w  w.  j  a va2 s. c o  m
@Override
public Object makeObject() throws Exception {
    int index = random.nextInt(addresses.size() - 1);
    ConnDesc desc = addresses.get(index);
    return new Socket(desc.getAddr(), desc.getPort());
}

From source file:net.mohatu.bloocoin.miner.SubmitList.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*  ww w  .  j  ava  2 s.  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:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public void sendSample(InetAddress host, int port, JSONObject sample) throws InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;/*w  ww  . j  a v  a 2 s.c  o m*/

    while (client == null || !client.isConnected()) {
        try {
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(sample.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);
}

From source file:com.nokia.dempsy.messagetransport.tcp.TcpSender.java

/**
 * This method is here for testing. It allows me to create a fake output stream that 
 * I can disrupt to test the behavior of network failures.
 *//*from  ww w . jav  a  2s.co m*/
protected Socket makeSocket(TcpDestination destination) throws IOException {
    return new Socket(destination.inetAddress, destination.port);
}

From source file:org.cloudfoundry.identity.uaa.login.test.IntegrationTestRule.java

private boolean connectionAvailable() {
    UriComponents components = UriComponentsBuilder.fromHttpUrl(baseUrl).build();
    String host = components.getHost();
    int port = components.getPort();

    logger.info("Testing connectivity for " + baseUrl);
    try (Socket socket = new Socket(host, port)) {
        logger.info("Connectivity test succeeded for " + baseUrl);
        return true;

    } catch (IOException e) {
        logger.warn("Connectivity test failed for " + baseUrl, e);
        return false;
    }//from ww  w .j a v  a2s  .c  o  m
}