Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:edu.mit.viral.shen.DroidFish.java

private void sendDataLocal(final int sq) {
    new Thread(new Runnable() {
        @Override/*from w  w w. j  av a2 s .  c om*/
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;
            try {
                socket = new Socket(Const.IP_ADD_LOCAL, 8890);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                String sq_string = Integer.toString(sq);
                dataOutputStream.writeUTF(sq_string);

            }

            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:edu.mit.viral.shen.DroidFish.java

private void sendComment(final String comment) {
    new Thread(new Runnable() {
        @Override/*from   ww  w  .  jav  a2  s  . co  m*/
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;
            try {
                // String[] words = longfen.split(" ");
                // String fen=words[0];               
                socket = new Socket(Const.IP_ADD_LOCAL, 8890);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(comment);

            }

            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:net.carlh.toast.Client.java

public void start(final String hostName, final int port)
        throws java.net.UnknownHostException, java.io.IOException {

    /* Thread to read stuff from the server */
    readThread = new Thread(new Runnable() {

        private byte[] getData(Socket socket, int length) {
            byte[] d = new byte[length];
            int offset = 0;
            while (offset < length) {
                try {
                    int t = socket.getInputStream().read(d, offset, length - offset);
                    if (t == -1) {
                        break;
                    }//from ww  w . j a va2s . c o  m
                    offset += t;
                } catch (SocketException e) {
                    /* This is probably because the socket has been closed in order to make
                       this thread terminate.
                    */
                    Log.e("Toast", "SocketException in client.getData", e);
                    break;
                } catch (IOException e) {
                    Log.e("Toast", "IOException in Client.getData()", e);
                    break;
                }
            }

            return java.util.Arrays.copyOf(d, offset);
        }

        public void run() {
            while (!stop.get()) {
                try {
                    synchronized (mutex) {
                        /* Connect */
                        socket = new Socket(hostName, port);
                        socket.setSoTimeout(timeout);
                    }

                    /* Keep going until there is a problem on read */

                    while (true) {
                        byte[] b = getData(socket, 4);

                        if (b.length != 4) {
                            break;
                        }

                        int length = ((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16) | ((b[2] & 0xff) << 8)
                                | (b[3] & 0xff);
                        if (length < 0 || length > (256 * 1024)) {
                            /* Don't like the sound of that */
                            Log.e("Toast", "Strange length " + length);
                            break;
                        }

                        byte[] d = getData(socket, length);

                        if (d.length != length) {
                            break;
                        }

                        try {
                            handler(new JSONObject(new String(d)));
                        } catch (JSONException e) {
                            Log.e("Toast", "Exception " + e.toString());
                        }
                    }

                    synchronized (mutex) {
                        /* Close the socket and go back round to connect again */
                        socket.close();
                        socket = null;
                    }

                } catch (ConnectException e) {
                    Log.e("Toast", "ConnectException");
                } catch (UnknownHostException e) {
                    Log.e("Toast", "UnknownHostException");
                } catch (IOException e) {
                    Log.e("Client", "IOException");
                } finally {
                    try {
                        Thread.sleep(timeout);
                    } catch (java.lang.InterruptedException e) {

                    }
                }
            }
        }
    });

    readThread.start();

    /* Thread to send stuff to the server */
    writeThread = new Thread(new Runnable() {

        public void run() {

            while (!stop.get()) {

                lock.lock();
                try {
                    while (toWrite.size() == 0 && !stop.get()) {
                        writeCondition.await();
                    }
                } catch (InterruptedException e) {

                } finally {
                    lock.unlock();
                }

                String s = null;
                lock.lock();
                if (toWrite.size() > 0) {
                    s = toWrite.get(0);
                    toWrite.remove(0);
                }
                lock.unlock();

                synchronized (mutex) {
                    try {
                        if (socket != null && s != null) {
                            socket.getOutputStream().write((s.length() >> 24) & 0xff);
                            socket.getOutputStream().write((s.length() >> 16) & 0xff);
                            socket.getOutputStream().write((s.length() >> 8) & 0xff);
                            socket.getOutputStream().write((s.length() >> 0) & 0xff);
                            socket.getOutputStream().write(s.getBytes());
                        }
                    } catch (IOException e) {
                        Log.e("Toast", "IOException in write");
                    }
                }
            }
        }
    });

    writeThread.start();

    /* Thread to send pings every so often */
    pingThread = new Thread(new Runnable() {
        public void run() {
            while (!stop.get()) {
                if (ping.get() == true && pong.get() == false) {
                    for (Handler h : handlers) {
                        h.sendEmptyMessage(0);
                    }
                    setConnected(false);
                }
                pong.set(false);
                try {
                    JSONObject json = new JSONObject();
                    json.put("type", "ping");
                    send(json);
                    ping.set(true);
                    Thread.sleep(pingInterval);
                } catch (JSONException e) {
                } catch (InterruptedException e) {
                }

            }
        }
    });

    pingThread.start();
}

From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java

public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException {
    final String methodName = IServiceCheckProcessor.CNAME
            + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException";

    if (DEBUG) {//  ww w .j a  v  a 2  s.c o m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServiceCheckRequest: {}", request);
    }

    int exitCode = -1;
    Socket socket = null;
    File sourceFile = null;
    CommandLine command = null;
    BufferedWriter writer = null;
    ExecuteStreamHandler streamHandler = null;
    ByteArrayOutputStream outputStream = null;
    ServiceCheckResponse response = new ServiceCheckResponse();

    final DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        switch (request.getRequestType()) {
        case NETSTAT:
            sourceFile = scriptConfig.getScripts().get("netstat");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        case REMOTEDATE:
            response.setRequestStatus(AgentStatus.SUCCESS);
            response.setResponseData(System.currentTimeMillis());

            break;
        case TELNET:
            response = new ServiceCheckResponse();

            int targetPort = request.getPortNumber();
            String targetServer = request.getTargetHost();

            if (DEBUG) {
                DEBUGGER.debug("Target port: {}", targetPort);
                DEBUGGER.debug("Target server: {}", targetServer);
            }

            if (targetPort == 0) {
                throw new ServiceCheckException("Target port number was not assigned. Cannot action request.");
            }

            final String CRLF = "\r\n";
            final String TERMINATE_TELNET = "^]";

            synchronized (new Object()) {
                InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort);

                socket = new Socket();
                socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT);
                socket.setSoLinger(false, 0);
                socket.setKeepAlive(false);

                try {
                    socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT);

                    if (!(socket.isConnected())) {
                        throw new ConnectException("Failed to connect to host " + targetServer + " on port "
                                + request.getPortNumber());
                    }

                    PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);
                    pWriter.println(TERMINATE_TELNET + CRLF);
                    pWriter.flush();
                    pWriter.close();

                    response.setRequestStatus(AgentStatus.SUCCESS);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " successful.");
                } catch (ConnectException cx) {
                    response.setRequestStatus(AgentStatus.FAILURE);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " failed with message: " + cx.getMessage());
                }
            }

            break;
        case PROCESSLIST:
            sourceFile = scriptConfig.getScripts().get("processList");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        default:
            // unknown operation
            throw new ServiceCheckException("No valid operation was specified");
        }
    } catch (UnknownHostException uhx) {
        ERROR_RECORDER.error(uhx.getMessage(), uhx);

        throw new ServiceCheckException(uhx.getMessage(), uhx);
    } catch (SocketException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new ServiceCheckException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ServiceCheckException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ServiceCheckException(ix.getMessage(), ix);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }

            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel payRequest(String strMachOrderId, Integer nTransactionAmount, String strTerminalId,
        String strTrackData, String strPIN, String strLongitude, String strLatitude, String host, Integer port,
        Integer nT0Flag, Integer marketType) {
    byte[] head = Device.nativeFunction1008(device);
    byte[] body = Device.nativeFunction1009(device, strMachOrderId, nTransactionAmount, strTerminalId,
            strTrackData, strPIN, strLongitude, strLatitude, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);/*from  ww  w  .jav a 2 s.  c om*/
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel newPayRequest(String strMachOrderId, Integer nTransactionAmount, String strTerminalId,
        String strTrackData, String strPIN, String strLongitude, String strLatitude, String host, Integer port,
        Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPIN)) {
            strPIN = strPIN + PIN_BACK;//  w  w  w  .ja  v a 2s.  c  o  m
        }
    }
    byte[] head = Device.nativeFunction1020(device);
    byte[] body = Device.nativeFunction1021(device, strMachOrderId, nTransactionAmount, strTerminalId,
            strTrackData, strPIN, strLongitude, strLatitude, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel ICCardPayRequest(String strMachOrderId, Integer nTransactionAmount, String strTerminalId,
        String strTrackData, String strPIN, String strLongitude, String strLatitude, String host, Integer port,
        String strCardSerialNo, String strICCardInfo, Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPIN)) {
            strPIN = strPIN + PIN_BACK;/* w  ww .j ava2s  .c om*/
        }
    }

    //        MyLog.info("mDealMode=", nT0Flag + "");
    byte[] head = Device.nativeFunction1020(device);
    byte[] body = Device.nativeFunction1023(device, strMachOrderId, nTransactionAmount, strTerminalId,
            strTrackData, strPIN, strLongitude, strLatitude, strCardSerialNo, strICCardInfo, nT0Flag,
            marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }
}

From source file:com.yeahka.android.lepos.Device.java

/**
 * ??//from   w ww  .jav a 2s  . co  m
 *
 * @param strOrderID
 * @param amount
 * @param strPinpadID
 * @param strTrack2Data
 * @param strTrack3Data
 * @param strPin
 * @param strLongitude
 * @param strLatitude
 * @param strCardSerialNo
 * @param strICCardInfo
 * @param strDiffuseFactor
 * @param deviceType
 * @param host
 * @param port
 * @return
 */
//-----------terence add --2016-03-17 t+0 ---------
//-----------terence add --2016-05-16   marketType---------
public ResultModel zhongciPayRequest(String strOrderID, Integer amount, String strPinpadID,
        String strTrack2Data, String strTrack3Data, String strPin, String strLongitude, String strLatitude,
        String strCardSerialNo, String strICCardInfo, String strDiffuseFactor, Integer deviceType, String host,
        Integer port, Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPin)) {
            strPin = strPin + PIN_BACK;
        }
    }
    //        String tag = "zhongciPayRequest";
    byte[] head = Device.nativeFunction10004(device);
    byte[] body = Device.nativeFunction10005(device, strOrderID, amount, strPinpadID, strTrack2Data,
            strTrack3Data, strPin, strLongitude, strLatitude, strCardSerialNo, strICCardInfo, strDiffuseFactor,
            deviceType, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            //                MyLog.d(TAG, "get head =" + bGetHead);
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            //                MyLog.d(TAG, "len is not 4 ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            //                MyLog.d(TAG, "data len less than 0 ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            //                MyLog.d(TAG, "len not equal data lenth ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        e.printStackTrace();
        MyLog.d(TAG, "UnknownHostException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        e1.printStackTrace();
        MyLog.d(TAG, "SocketException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        e2.printStackTrace();
        MyLog.d(TAG, "IOException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel sendDataToRegisterServer(byte[] data, Class classOfT) {
    String host = REGISTER_HOST; // "192.168.21.243";
    int port = REGISTER_PORT; // 8061;
    InetAddress address;/*from  w  w w  . j a  v a 2 s  . c  o  m*/
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(data);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket,
                ServerSocketConnectUtil.HEAD_TYPE_REGISTER_SYSTEM);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntHighByteFirst(); // readIntHighByteFirst
        // readIntLowByteFirst
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        while (length < dataLength) {
            length += input.read(bytes, length, dataLength - length);
        }

        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        byte[] bytesMsgHeader = new byte[4];
        System.arraycopy(bytes, 0, bytesMsgHeader, 0, 4);
        if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_HEADER,
                bytesMsgHeader)) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        System.arraycopy(bytes, 4, bytesMsgHeader, 0, 4);
        bar = new ByteArrayReader(bytesMsgHeader);
        length = bar.readIntHighByteFirst();

        int index = 8 + length;
        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;
        if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_BODY,
                bytesMsgHeader)) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;

        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;
        if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_BODY_CONTENT,
                bytesMsgHeader)) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;
        bar = new ByteArrayReader(bytesMsgHeader);
        length = bar.readIntHighByteFirst();

        if (dataLength < index + length) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        byte[] josnBytes = new byte[length];
        System.arraycopy(bytes, index, josnBytes, 0, length);

        ResultModel resultModel = new ResultModel(josnBytes, classOfT);

        // if (bNeedRecycleRegisterServerSocket) {
        // out.close();
        // input.close();
        // registerServerSocket.close();
        // registerServerSocket = null;
        // }

        return resultModel;
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }
}