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.blade.BladeTestCase.java

@SuppressWarnings("resource")
@Test/*ww  w  .java  2 s  . c o  m*/
public void testStartStopServer() throws Exception {
    Blade blade = Blade.me();
    blade.listen(10241).start();
    try {
        HttpResponse response = Request.Get("http://localhost:10241/").execute().returnResponse();
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 404);
    } finally {
        blade.stop();
        try {
            new Socket("localhost", 10241);
            Assert.fail("Server is still running");
        } catch (ConnectException e) {
        }
    }
}

From source file:bankingclient.TaoTaiKhoanFrame.java

public TaoTaiKhoanFrame(NewOrOldAccFrame acc) {

    initComponents();//from www . j  a  v  a 2 s.  co m
    this.jText_ten_tk.setText("");
    this.jText_sd.setText("");

    this.noAcc = acc;
    this.mainCustomerName = null;
    this.setVisible(false);

    jBt_ht.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jText_sd.getText()) && (Long.parseLong(jText_sd.getText()) > 0)) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(3);
                    dout.writeUTF(jText_ten_tk.getText() + "\n" + mainCustomerName + "\n" + jText_sd.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da tao tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "tao tai khoan khong thanh cong");
                    }
                    client.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                noAcc.setVisible(true);
                TaoTaiKhoanFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane, "Can nhap lai so tien gui");
            }

        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            TaoTaiKhoanFrame.this.setVisible(false);

        }
    });
}

From source file:expect4j.ExpectUtils.java

/**
 * Creates an HTTP client connection to a specified HTTP server and
 * returns the entire response.  This function simulates <code>curl
 * http://remotehost/url</code>./* ww w .  ja  v  a 2  s.  c  om*/
 *
 * @param remotehost the DNS or IP address of the HTTP server
 * @param url the path/file of the resource to look up on the HTTP
 *        server
 * @return the response from the HTTP server
 * @throws Exception upon a variety of error conditions
 */
public static String Http(String remotehost, String url) throws Exception {
    Socket s = null;
    s = new Socket(remotehost, 80);
    logger.debug("Connected to " + s.getInetAddress().toString());

    if (false) {
        // for serious connection-oriented debugging only
        PrintWriter out = new PrintWriter(s.getOutputStream(), false);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        System.out.println("Sending request");
        out.print("GET " + url + " HTTP/1.1\r\n");
        out.print("Host: " + remotehost + "\r\n");
        out.print("Connection: close\r\n");
        out.print("User-Agent: Expect4j\r\n");
        out.print("\r\n");
        out.flush();
        System.out.println("Request sent");

        System.out.println("Receiving response");
        String line;
        while ((line = in.readLine()) != null)
            System.out.println(line);
        System.out.println("Received response");
        if (line == null)
            System.exit(0);
    }

    Expect4j expect = new Expect4j(s);

    logger.debug("Sending HTTP request for " + url);
    expect.send("GET " + url + " HTTP/1.1\r\n");
    expect.send("Host: " + remotehost + "\r\n");
    expect.send("Connection: close\r\n");
    expect.send("User-Agent: Expect4j\r\n");
    expect.send("\r\n");

    logger.debug("Waiting for HTTP response");
    String remaining = null;
    expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected HTTP Response Header");

            // save http code
            String match = state.getMatch();
            String parts[] = match.split(" ");

            state.addVar("httpCode", parts[1]);
            state.exp_continue();
        }
    }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected Content-Type header");
            state.addVar("contentType", state.getMatch());
            state.exp_continue();
        }
    }), new EofMatch(new Closure() { // should cause entire page to be collected
        public void run(ExpectState state) {
            logger.trace("Found EOF, done receiving HTTP response");
        }
    }), // Will cause buffer to be filled up till end
            new TimeoutMatch(10000, new Closure() {
                public void run(ExpectState state) {
                    logger.trace("Timeout waiting for HTTP response");
                }
            }) });

    remaining = expect.getLastState().getBuffer(); // from EOF matching

    String httpCode = (String) expect.getLastState().getVar("httpCode");

    String contentType = (String) expect.getLastState().getVar("contentType");

    s.close();

    return remaining;
}

From source file:Dengue.CDengueManager.java

private static void sendInfoToCPU(String pStrJSON, int pIntPort) {

    new Thread(() -> {
        try (Socket client = new Socket(InetAddress.getLocalHost(), pIntPort)) {

            Writer objWriter = Channels.newWriter(Channels.newChannel(client.getOutputStream()),
                    StandardCharsets.US_ASCII.name());
            objWriter.write(pStrJSON);/*from   w w w  .ja  va2  s.  c o m*/
            objWriter.flush();

            client.shutdownOutput();

            try (Reader objReader = Channels.newReader(Channels.newChannel(client.getInputStream()),
                    StandardCharsets.US_ASCII.name());
                    BufferedReader objOutReader = new BufferedReader(objReader)) {
                System.out.println((char) objOutReader.read());

            }

        } catch (IOException e) {
            System.out.println(e);
        }
    }).start();
}

From source file:delete.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w  w .  java 2 s .c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    Socket s = new Socket("localhost", 9999);

    DataInputStream in = new DataInputStream(s.getInputStream());
    DataOutputStream outD = new DataOutputStream(s.getOutputStream());

    outD.writeUTF(request.getParameter("employee_id"));

    in.readUTF();

    s.close();

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println("Deleted");
    }
}

From source file:me.mgray.universalremote.client.model.ServerConnector.java

public void connect() {
    try {//from ww  w .  j a  v  a  2  s . c  om
        serverConnection = new Connection(new Socket(hostname, port));
        // Upon connection, server will give the session id
        sessionId = serverConnection.read();
        EventBus.publish(new SessionIdRecievedEvent(sessionId));
        // Listen for commands
        socketListener.execute(new CommandListener(serverConnection));
    } catch (UnknownHostException e) {
        System.err.println(String.format("Don't know about host: %s", hostname));
        System.exit(1);
    } catch (IOException e) {
        System.err.println(String.format("Couldn't get I/O for the connection to: %s:%d", hostname, port));
        System.exit(1);
    }
}

From source file:com.muleinaction.GreenMailUtilities.java

public static void waitForStartup(String host, int port, int count, long wait) throws InterruptedException {
    for (int i = 0; i < count; ++i) {
        Thread.sleep(wait);//w  ww  .  j a  v  a  2s .c  om
        try {
            Socket socket = new Socket(host, port);
            socket.close();
            logger.info("Successful connection made to port " + port);
            return;
        } catch (Exception e) {
            logger.warn("Could not connect to server on " + host + ":" + port + " - " + e.getMessage());
        }
    }
    throw new RuntimeException("Server failed to start within " + (count * wait) + "ms");
}

From source file:me.mast3rplan.phantombot.HTTPResponse.java

HTTPResponse(String address, String request) throws IOException {

    Socket sock = new Socket(address, 80);
    Writer output = new StringWriter();
    IOUtils.write(request, sock.getOutputStream(), "utf-8");
    IOUtils.copy(sock.getInputStream(), output);
    com.gmt2001.Console.out.println(output.toString());
    Scanner scan = new Scanner(sock.getInputStream());
    String errorLine = scan.nextLine();
    for (String line = scan.nextLine(); !line.equals(""); line = scan.nextLine()) {
        String[] keyval = line.split(":", 2);
        if (keyval.length == 2) {
            values.put(keyval[0], keyval[1].trim());
        } else {/* w  ww . ja v a2 s . c o m*/
            //?
        }
    }
    while (scan.hasNextLine()) {
        body += scan.nextLine();
    }
    sock.close();

}

From source file:mc.lib.network.NetworkHelper.java

private static boolean testConnection(String url) {
    Socket s = null;/*  ww  w .  j  a  v  a2 s  .  c om*/
    boolean res = false;
    try {
        s = new Socket(url, 80);
        if (s.isBound() && s.isConnected()) {
            res = true;
        }
    } catch (IOException e) {
        Log.e(LOGTAG, "Error on testConnection to " + url, e);
    } finally {
        if (s != null)
            StreamHelper.close(s);
    }
    return res;
}

From source file:bankingclient.DKFrame.java

public DKFrame(MainFrame vmain) {
    initComponents();/* w w w . ja  va  2 s.  c o m*/
    this.main = vmain;
    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField3.setText("");
    this.jTextField4.setText("");
    this.jTextField5.setText("");
    this.setVisible(false);
    jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jTextField2.getText().equals(jTextField3.getText())
                    && NumberUtils.isNumber(jTextField4.getText())
                    && NumberUtils.isNumber(jTextField5.getText())) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    String cusName = jTextField1.getText();
                    String pass = jTextField2.getText();
                    String sdt = jTextField4.getText();
                    String cmt = jTextField5.getText();
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(1);
                    dout.writeUTF(cusName + "\n" + pass + "\n" + sdt + "\n" + cmt);
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da dang ki tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "dang ki tai khoan khong thanh cong");

                    }
                    client.close();
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
                main.setVisible(true);
                DKFrame.this.setVisible(false);

            } else {
                JOptionPane.showMessageDialog(rootPane, "Nhap thong tin sai, moi nhap lai");
            }
        }
    });
    jButton2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DKFrame.this.setVisible(false);
        }
    });
}