Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.twinflag.coofiletouch.AuthorityChecking.java

private void fetchLicenseFromInternet() {
    Log.i(TAG, "===fetchLicenseFromInternet !");
    new Thread() {
        public void run() {
            try {
                JSONObject json = new JSONObject();
                try {
                    int readLength = 0;
                    int sendSize = 0;
                    json.put("command", "checkLicense");
                    json.put("hardinfo", DeviceUtil.getDeviceInfo());

                    Socket socket = new Socket("192.168.13.95", 60000);

                    // ?
                    OutputStream os = socket.getOutputStream();
                    String jsonStr = json.toString();
                    byte[] buffer = jsonStr.getBytes("UTF-8");
                    sendSize = buffer.length;
                    byte[] array = new byte[4];
                    array[3] = (byte) (0xff & sendSize);
                    array[2] = (byte) ((0xff00 & sendSize) >> 8);
                    array[1] = (byte) ((0xff0000 & sendSize) >> 16);
                    array[0] = (byte) (0xff000000 & sendSize >> 24);
                    os.write(array);/* w w  w .  java2s.c o m*/
                    os.flush();
                    os.write(buffer);
                    os.flush();

                    // ;
                    InputStream inputStream = socket.getInputStream();
                    byte[] length = new byte[4];
                    byte[] temp = new byte[4];
                    byte oneByte;
                    try {
                        inputStream.read(length);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    for (int i = 0; i < 4; i++) {
                        temp[3 - i] = length[i];
                    }
                    for (int j = 0; j < 4; j++) {
                        oneByte = temp[j];
                        readLength += (oneByte & 0xFF) << (8 * j);
                    }

                    System.out.println(readLength + "?");

                    if (readLength == 0) {
                        System.out.println("readLength == 0");
                        Message msg = Message.obtain();
                        msg.what = MSG_GET_LINCENSE_FROM_INTERNET;
                        msg.obj = null;
                        mHandler.sendMessageDelayed(msg, 100);
                    }
                    // ??0
                    else {
                        System.out.println("readLength == " + readLength);
                        buffer = new byte[readLength];
                        try {
                            String receivedContent = null;
                            inputStream.read(buffer, 0, readLength);
                            receivedContent = new String(buffer, "UTF-8");

                            Message msg = Message.obtain();
                            msg.what = MSG_GET_LINCENSE_FROM_INTERNET;
                            msg.obj = receivedContent;
                            mHandler.sendMessageDelayed(msg, 100);

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

                } catch (JSONException exception) {
                    exception.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();

}

From source file:com.raddle.tools.ClipboardTransferMain.java

private void setRemoteClipboard(boolean alert) {
    if (!isProcessing) {
        isProcessing = true;/*from   w  ww  . j  a  va 2  s  .c  o  m*/
        try {
            Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
            Transferable clipT = sysc.getContents(null);
            if (alert && !ClipboardUtils.isClipboardNotEmpty(clipT)) {
                updateMessage("?");
                return;
            }
            updateMessage("???");
            trayIcon.setImage(sendImage);
            final BooleanHolder success = new BooleanHolder();
            doInSocket(new SocketCallback() {

                @Override
                public Object connected(Socket socket) throws Exception {
                    ClipCommand cmd = new ClipCommand();
                    cmd.setCmdCode(ClipCommand.CMD_SET_CLIP);
                    cmd.setResult(ClipboardUtils.getClipResult());
                    // ??
                    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                    out.writeObject(cmd);
                    // 
                    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                    ClipResult result = (ClipResult) in.readObject();
                    if (result.isSuccess()) {
                        StringBuilder sb = new StringBuilder();
                        for (DataFlavor dataFlavor : cmd.getResult().getClipdata().keySet()) {
                            sb.append("\n");
                            sb.append(dataFlavor.getPrimaryType()).append("/").append(dataFlavor.getSubType());
                        }
                        iconQueue.add("send");
                        success.value = true;
                        updateMessage("????? " + sb);
                    } else {
                        updateMessage("???:" + result.getMessage());
                    }
                    in.close();
                    out.close();
                    return null;
                }
            });
            if (!success.value) {
                trayIcon.setImage(grayImage);
            }
        } catch (Exception e) {
            trayIcon.setImage(grayImage);
            updateMessage("???" + e.getMessage());
        } finally {
            isProcessing = false;
        }
    }
}

From source file:net.ostis.sc.memory.impl.remote.rgp.RGPSession.java

public RGPSession(RGPMemory memory, Socket controlSocket, Socket eventSocket)
        throws IOException, RGPProtocolException {
    this.memory = memory;
    this.controlSocket = controlSocket;
    this.eventSocket = eventSocket;
    this.objectsRegistry = new RGPObjectsRegistry(this);
    this.controlStream = new RGPProtocolStream(controlSocket.getInputStream(), controlSocket.getOutputStream(),
            objectsRegistry);/*from  ww w.  j a  v a 2 s  . c  om*/
    this.eventStream = new RGPProtocolStream(eventSocket.getInputStream(), eventSocket.getOutputStream(),
            objectsRegistry);

    eventThread = new Thread(this);
    eventThread.setName("RGP Events Listener");
    eventThread.setDaemon(true);
    eventThread.start();

    login();
}

From source file:bankingclient.ChonThaoTacFrame.java

public ChonThaoTacFrame(NewOrOldAccFrame acc) {
    initComponents();//from   w  w  w .j av a2  s.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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private void runSimultaneousDataExchange(boolean useTunnel, int nclients)
        throws IOException, InterruptedException, NoSuchAlgorithmException {
    long t0 = System.currentTimeMillis();
    final int nMsgs = 50;
    final Map<String, MessageDigest> digestMsgsRecvdAtServer = new HashMap<String, MessageDigest>();
    final Map<String, MessageDigest> digestMsgsSentByClients = new HashMap<String, MessageDigest>();
    final Map<String, MessageDigest> digestMsgsRecvdAtClients = new HashMap<String, MessageDigest>();
    for (int c = 0; c < nclients; c++) {
        digestMsgsRecvdAtServer.put(Integer.toString(c), MessageDigest.getInstance("MD5"));
        digestMsgsSentByClients.put(Integer.toString(c), MessageDigest.getInstance("MD5"));
        digestMsgsRecvdAtClients.put(Integer.toString(c), MessageDigest.getInstance("MD5"));
    }/*from   w w  w.  j a v a  2  s  .  com*/
    final MessageDigest digestMsgsSentByServer = MessageDigest.getInstance("MD5");
    for (int i = 0; i < nMsgs; i++) {
        digestMsgsSentByServer.update(TalkPastServer.generateMsgFromServer(i).getBytes());
    }
    String hashOfMsgsSentByServer = Hex.encodeHexString(digestMsgsSentByServer.digest());

    MockServer talkPastServer = startTalkPastServer(nMsgs, digestMsgsRecvdAtServer);

    int targetPort = talkPastServer.getServerSocketPort();
    Tunnel tunnel = null;
    MockServer proxyServer = null;
    if (useTunnel) {
        proxyServer = startConnectProxyServer();
        tunnel = Tunnel.build("localhost", talkPastServer.getServerSocketPort(), "localhost",
                proxyServer.getServerSocketPort());
        targetPort = tunnel.getPort();
    }

    try {
        List<EasyThread> clientThreads = new ArrayList<EasyThread>();
        final int portToUse = targetPort;
        for (int c = 0; c < nclients; c++) {
            final int clientId = c;
            clientThreads.add(new EasyThread() {
                @Override
                void runQuietly() throws Exception {
                    long t = System.currentTimeMillis();
                    LOG.info("\t" + clientId + ": Client starting");
                    final MessageDigest digestMsgsRecvdAtClient = digestMsgsRecvdAtClients
                            .get(Integer.toString(clientId));
                    //final SocketChannel client = SocketChannel.open(); // tunnel test hangs for some reason with SocketChannel
                    final Socket client = new Socket();
                    client.connect(new InetSocketAddress("localhost", portToUse));
                    EasyThread serverReaderThread = new EasyThread() {
                        @Override
                        public void runQuietly() {
                            try {
                                BufferedReader clientIn = new BufferedReader(
                                        new InputStreamReader(client.getInputStream()));
                                String line = clientIn.readLine();
                                while (line != null && !line.equals("Goodbye")) {
                                    //LOG.info("\t" + clientId + ": Server said [" + line.substring(0, 32) + "... ]");
                                    digestMsgsRecvdAtClient.update(line.getBytes());
                                    digestMsgsRecvdAtClient.update("\n".getBytes());
                                    line = clientIn.readLine();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            LOG.info("\t" + clientId + ": Client done reading");
                        }
                    }.startThread();

                    MessageDigest hashMsgsFromClient = digestMsgsSentByClients.get(Integer.toString(clientId));
                    BufferedOutputStream clientOut = new BufferedOutputStream(client.getOutputStream());
                    for (int i = 0; i < nMsgs; i++) {
                        String msg = clientId + ":" + i + " " + StringUtils.repeat("Blahhh Blahhh ", 10000)
                                + "\n";
                        //LOG.info(clientId + " sending " + msg.length() + " bytes");
                        byte[] bytes = msg.getBytes();
                        hashMsgsFromClient.update(bytes);
                        clientOut.write(bytes);
                        MockServer.sleepQuietly(2);
                    }
                    clientOut.write(("Goodbye\n".getBytes()));
                    clientOut.flush();
                    LOG.info("\t" + clientId + ": Client done writing in " + (System.currentTimeMillis() - t)
                            + " ms");
                    serverReaderThread.join();
                    LOG.info("\t" + clientId + ": Client done in " + (System.currentTimeMillis() - t) + " ms");
                    client.close();
                }
            }.startThread());
        }
        for (Thread clientThread : clientThreads) {
            clientThread.join();
        }
        LOG.info("All data transfer done in " + (System.currentTimeMillis() - t0) + " ms");
    } finally {
        talkPastServer.stopServer();
        if (tunnel != null) {
            proxyServer.stopServer();
            tunnel.close();
            assertFalse(tunnel.isTunnelThreadAlive());
            assertEquals(proxyServer.getNumConnects(), nclients);
        }

        Map<String, String> hashOfMsgsRecvdAtServer = new HashMap<String, String>();
        Map<String, String> hashOfMsgsSentByClients = new HashMap<String, String>();
        Map<String, String> hashOfMsgsRecvdAtClients = new HashMap<String, String>();
        for (int c = 0; c < nclients; c++) {
            String client = Integer.toString(c);
            hashOfMsgsRecvdAtServer.put(client,
                    Hex.encodeHexString(digestMsgsRecvdAtServer.get(client).digest()));
            hashOfMsgsSentByClients.put(client,
                    Hex.encodeHexString(digestMsgsSentByClients.get(client).digest()));
            hashOfMsgsRecvdAtClients.put(client,
                    Hex.encodeHexString(digestMsgsRecvdAtClients.get(client).digest()));
        }

        LOG.info("\tComparing client sent to server received");
        assertEquals(hashOfMsgsSentByClients, hashOfMsgsRecvdAtServer);

        LOG.info("\tComparing server sent to client received");
        for (String hashOfMsgsRecvdAtClient : hashOfMsgsRecvdAtClients.values()) {
            assertEquals(hashOfMsgsSentByServer, hashOfMsgsRecvdAtClient);
        }
        LOG.info("\tDone");
    }
}

From source file:com.hijacker.MainActivity.java

static Socket connect() {
    //Can be called from any thread, blocks until the job is finished
    Socket socket;
    try {//from   w  w w . ja va 2 s  .co m
        InetAddress ip = Inet4Address.getByName(SERVER);
        socket = new Socket();
        socket.connect(new InetSocketAddress(ip, PORT), 2000);

        PrintWriter in = new PrintWriter(socket.getOutputStream());
        BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //Authenticate (receive a string generated by the server, combine it with a stored key and send back the hashcode)
        if (debug)
            Log.d("HIJACKER/connect", "Authenticating with server...");
        String temp = out.readLine() + AUTH_KEY;
        in.print(Integer.toString(temp.hashCode()) + '\n');
        in.flush();

        temp = out.readLine();
        if (temp != null) {
            if (!temp.equals(ANS_POSITIVE))
                return null; //Not authenticated, socket will be closed by the server
        } else
            return null; //Connection closed, probably not authenticated
        if (debug)
            Log.d("HIJACKER/connect", "Authenticated");

        if (deviceID == -1) {
            if (debug)
                Log.d("HIJACKER/connect", "Getting new deviceID...");
            in.print(REQ_NEW_ID + '\n');
            in.flush();

            try {
                deviceID = Long.parseLong(out.readLine());
                if (pref_edit != null) {
                    pref_edit.putLong("deviceID", deviceID);
                    pref_edit.commit();
                }
                if (debug)
                    Log.d("HIJACKER/connect", "New deviceID is " + deviceID);
            } catch (NumberFormatException ignored) {
                if (debug)
                    Log.d("HIJACKER/connect", "deviceID caused NumberFormatException, still -1");
            }
        }
        //String should be: info APP_VERSION_NAME APP_VERSION_CODE ANDROID_VERSION DEVICE_MODEL DEVICE_ID
        in.print(REQ_INFO + " " + versionName + " " + versionCode + " " + Build.VERSION.SDK_INT + " "
                + deviceModel + " " + deviceID + '\n');
        in.flush();
    } catch (IOException e) {
        Log.e("HIJACKER/connect", e.toString());
        return null;
    }
    return socket;
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??sendManagerDiscoveryInfo?//from ww  w  .j a va 2s .c o  m
 * TCP 24005?????????IP?
 * 
 * @throws Exception
 */
private String receiveManagerDiscoveryInfo() throws Exception {
    int default_port = 24005;
    String portStr = AgentProperties.getProperty("discovery.pingport", Integer.toString(default_port));
    int port = Integer.parseInt(portStr);
    if (port < 1 || port > 65535) {
        port = default_port;
    }
    ServerSocket servSock = null;
    Socket clntSock = null;

    final int BUFSIZE = 256;
    int tmpRecvMsgSize = 0;
    int recvMsgSize = 0;
    byte[] receiveBuf = new byte[BUFSIZE];
    String recvMsg = "";

    try {
        servSock = new ServerSocket(port);

        // ????
        clntSock = servSock.accept();
        m_log.info("connecting to " + clntSock.getRemoteSocketAddress().toString());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        while ((tmpRecvMsgSize = in.read(receiveBuf)) != -1) {
            out.write(receiveBuf, 0, tmpRecvMsgSize);
            recvMsgSize = tmpRecvMsgSize;
        }

        recvMsg = new String(receiveBuf, 0, recvMsgSize);
        m_log.info("receive message : " + recvMsg);
    } catch (Exception e) {
        m_log.warn("receiveManagerIp " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    } finally {
        try {
            if (clntSock != null) {
                clntSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
        try {
            if (servSock != null) {
                servSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
    }
    return recvMsg;
}

From source file:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java

private void showIgv(final Object chrom, final Object pos) {
    if (igvIP == null || igvPort == null)
        return;//  ww w.java  2 s  . co  m
    Thread thread = new Thread() {
        @Override
        public void run() {
            PrintWriter out = null;
            BufferedReader in = null;
            Socket socket = null;

            try {
                socket = new Socket(igvIP, igvPort);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out.println("goto " + chrom + ":" + pos);
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException err2) {
                }
            } catch (Exception err) {
                LOG.info("" + err.getMessage());
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (Exception err) {
                    }
                if (out != null)
                    try {
                        out.close();
                    } catch (Exception err) {
                    }
                if (socket != null)
                    try {
                        socket.close();
                    } catch (Exception err) {
                    }
            }
        }
    };
    thread.start();
}

From source file:android.core.SSLSocketTest.java

/**
 * Regression test for problem where close() resulted in a hand if
 * a different thread was sitting in a blocking read or write.
 *//* www  .j a v  a 2 s  .co m*/
public void testMultithreadedClose() throws Exception {
    InetSocketAddress address = new InetSocketAddress("www.fortify.net", 443);
    final Socket socket = clientFactory.createSocket();
    socket.connect(address);

    Thread reader = new Thread() {
        @Override
        public void run() {
            try {
                byte[] buffer = new byte[512];
                InputStream stream = socket.getInputStream();
                socket.getInputStream().read(buffer);
            } catch (Exception ex) {
                android.util.Log.d("SSLSocketTest", "testMultithreadedClose() reader got " + ex.toString());
            }
        }
    };

    Thread closer = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                socket.close();
            } catch (Exception ex) {
                android.util.Log.d("SSLSocketTest", "testMultithreadedClose() closer got " + ex.toString());
            }
        }
    };

    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting reader...");
    reader.start();
    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting closer...");
    closer.start();

    long t1 = System.currentTimeMillis();
    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining reader...");
    reader.join(30000);
    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining closer...");
    closer.join(30000);
    long t2 = System.currentTimeMillis();

    assertTrue("Concurrent close() hangs", t2 - t1 < 30000);
}

From source file:com.cbsb.ftpserv.ProxyConnector.java

/**
 * Connects an outgoing socket to the proxy and authenticates, creating an account
 * if necessary./*from ww w .j  a  v a  2  s .  co m*/
 */
private Socket newAuthedSocket(String hostname, int port) {
    if (hostname == null) {
        myLog.i("newAuthedSocket can't connect to null host");
        return null;
    }
    JSONObject json = new JSONObject();
    //String secret = retrieveSecret();
    Socket socket;
    OutputStream out = null;
    InputStream in = null;

    try {
        myLog.d("Opening proxy connection to " + hostname + ":" + port);
        socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
        json.put("android_id", Util.getAndroidId());
        json.put("swiftp_version", Util.getVersion());
        json.put("action", "login");
        out = socket.getOutputStream();
        in = socket.getInputStream();
        int numBytes;

        out.write(json.toString().getBytes(ENCODING));
        myLog.l(Log.DEBUG, "Sent login request");
        // Read and parse the server's response
        byte[] bytes = new byte[IN_BUF_SIZE];
        // Here we assume that the server's response will all be contained in
        // a single read, which may be unsafe for large responses
        numBytes = in.read(bytes);
        if (numBytes == -1) {
            myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
            return null;
        } else if (numBytes == 0) {
            myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
            return null;
        }
        json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
        if (checkAndPrintJsonError(json)) {
            return null;
        }
        myLog.d("newAuthedSocket successful");
        return socket;
    } catch (Exception e) {
        myLog.i("Exception during proxy connection or authentication: " + e);
        return null;
    }
}