Example usage for java.net Socket setKeepAlive

List of usage examples for java.net Socket setKeepAlive

Introduction

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

Prototype

public void setKeepAlive(boolean on) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_KEEPALIVE SO_KEEPALIVE .

Usage

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter
 * <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl
 * socket factory/*from w w  w  . j  a  v a  2 s  .c o  m*/
 */
public Socket connect(InetAddress inetadd, int port, int timeout, ConnectionWatcher optionalWatcher,
        boolean clientSide, int socketBufferSize, boolean sslConnection) throws IOException {
    Socket socket = null;
    SocketAddress sockaddr = new InetSocketAddress(inetadd, port);
    printConfig();
    try {
        if (sslConnection) {
            if (this.sslContext == null) {
                throw new GemFireConfigException("SSL not configured correctly, Please look at previous error");
            }
            SocketFactory sf = this.sslContext.getSocketFactory();
            socket = sf.createSocket();

            // Optionally enable SO_KEEPALIVE in the OS network protocol.
            socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);

            // If necessary, set the receive buffer size before connecting the
            // socket so that large buffers will be allocated on accepted sockets
            // (see java.net.Socket.setReceiverBufferSize javadocs for details)
            if (socketBufferSize != -1) {
                socket.setReceiveBufferSize(socketBufferSize);
            }

            if (optionalWatcher != null) {
                optionalWatcher.beforeConnect(socket);
            }
            socket.connect(sockaddr, Math.max(timeout, 0));
            configureClientSSLSocket(socket, timeout);
            return socket;
        } else {
            if (clientSide && this.clientSocketFactory != null) {
                socket = this.clientSocketFactory.createSocket(inetadd, port);
            } else {
                socket = new Socket();

                // Optionally enable SO_KEEPALIVE in the OS network protocol.
                socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);

                // If necessary, set the receive buffer size before connecting the
                // socket so that large buffers will be allocated on accepted sockets
                // (see java.net.Socket.setReceiverBufferSize javadocs for details)
                if (socketBufferSize != -1) {
                    socket.setReceiveBufferSize(socketBufferSize);
                }

                if (optionalWatcher != null) {
                    optionalWatcher.beforeConnect(socket);
                }
                socket.connect(sockaddr, Math.max(timeout, 0));
            }
            return socket;
        }
    } finally {
        if (optionalWatcher != null) {
            optionalWatcher.afterConnect(socket);
        }
    }
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/** Setup all socket options.  Should be called before any read/write
 * calls *///from w ww  .  j  av a2  s.  co  m
void setupOpenSocket(Socket sock) throws SocketException {
    if (log.isDebug3()) {
        log.debug3(sock + "SO_TIMEOUT: " + getSoTimeout() + ", TcpNoDelay: " + isTcpNoDelay() + ", KeepAlive: "
                + paramSoKeepAlive);
    }
    sock.setSoTimeout((int) getSoTimeout());
    sock.setTcpNoDelay(isTcpNoDelay());
    sock.setKeepAlive(paramSoKeepAlive);
}

From source file:com.mirth.connect.connectors.tcp.TcpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage message) {
    TcpDispatcherProperties tcpDispatcherProperties = (TcpDispatcherProperties) connectorProperties;
    Status responseStatus = Status.QUEUED;
    String responseData = null;//from w w w.  j  a  va 2s.c o  m
    String responseStatusMessage = null;
    String responseError = null;
    boolean validateResponse = false;

    long dispatcherId = getDispatcherId();

    String socketKey = dispatcherId + tcpDispatcherProperties.getRemoteAddress()
            + tcpDispatcherProperties.getRemotePort();
    if (tcpDispatcherProperties.isOverrideLocalBinding()) {
        socketKey += tcpDispatcherProperties.getLocalAddress() + tcpDispatcherProperties.getLocalPort();
    }

    Socket socket = null;
    Thread timeoutThread = null;

    try {
        // Do some validation first to avoid unnecessarily creating sockets
        if (StringUtils.isBlank(tcpDispatcherProperties.getRemoteAddress())) {
            throw new Exception("Remote address is blank.");
        } else if (NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()) <= 0) {
            throw new Exception("Remote port is invalid.");
        }

        socket = connectedSockets.get(socketKey);
        timeoutThread = timeoutThreads.get(socketKey);

        // If keep connection open is true, then interrupt the thread so it won't close the socket
        if (tcpDispatcherProperties.isKeepConnectionOpen() && timeoutThread != null) {
            disposeThreadQuietly(socketKey);
        }

        // Initialize a new socket if our current one is invalid, the remote side has closed, or keep connection open is false
        if (!tcpDispatcherProperties.isKeepConnectionOpen() || socket == null || socket.isClosed()
                || (tcpDispatcherProperties.isCheckRemoteHost() && socket instanceof StateAwareSocketInterface
                        && ((StateAwareSocketInterface) socket).remoteSideHasClosed())) {
            closeSocketQuietly(socketKey);

            logger.debug("Creating new socket (" + connectorProperties.getName() + " \"" + getDestinationName()
                    + "\" on channel " + getChannelId() + ").");
            String info = "Trying to connect on " + tcpDispatcherProperties.getRemoteAddress() + ":"
                    + tcpDispatcherProperties.getRemotePort() + "...";
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.CONNECTING, info));

            if (tcpDispatcherProperties.isOverrideLocalBinding()) {
                socket = SocketUtil.createSocket(configuration, tcpDispatcherProperties.getLocalAddress(),
                        NumberUtils.toInt(tcpDispatcherProperties.getLocalPort()));
            } else {
                socket = SocketUtil.createSocket(configuration);
            }

            ThreadUtils.checkInterruptedStatus();
            connectedSockets.put(socketKey, socket);

            SocketUtil.connectSocket(socket, tcpDispatcherProperties.getRemoteAddress(),
                    NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()), responseTimeout);

            socket.setReuseAddress(true);
            socket.setReceiveBufferSize(bufferSize);
            socket.setSendBufferSize(bufferSize);
            socket.setSoTimeout(responseTimeout);
            socket.setKeepAlive(tcpDispatcherProperties.isKeepConnectionOpen());

            eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.CONNECTED,
                    SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket), true));
        }

        ThreadUtils.checkInterruptedStatus();

        // Send the message
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.SENDING,
                SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket)));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), bufferSize);
        BatchStreamReader batchStreamReader = new DefaultBatchStreamReader(socket.getInputStream());
        StreamHandler streamHandler = transmissionModeProvider.getStreamHandler(socket.getInputStream(), bos,
                batchStreamReader, tcpDispatcherProperties.getTransmissionModeProperties());
        streamHandler.write(getTemplateBytes(tcpDispatcherProperties, message));
        bos.flush();

        if (!tcpDispatcherProperties.isIgnoreResponse()) {
            ThreadUtils.checkInterruptedStatus();

            // Attempt to get the response from the remote endpoint
            try {
                String info = "Waiting for response from " + SocketUtil.getInetAddress(socket) + " (Timeout: "
                        + tcpDispatcherProperties.getResponseTimeout() + " ms)... ";
                eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                        getDestinationName(), ConnectionStatusEventType.WAITING_FOR_RESPONSE, info));
                byte[] responseBytes = streamHandler.read();
                if (responseBytes != null) {
                    responseData = new String(responseBytes,
                            CharsetUtils.getEncoding(tcpDispatcherProperties.getCharsetEncoding()));
                    responseStatusMessage = "Message successfully sent.";
                } else {
                    responseStatusMessage = "Message successfully sent, but no response received.";
                }

                streamHandler.commit(true);
                responseStatus = Status.SENT;

                // We only want to validate the response if we were able to retrieve it successfully
                validateResponse = tcpDispatcherProperties.getDestinationConnectorProperties()
                        .isValidateResponse();
            } catch (IOException e) {
                // An exception occurred while retrieving the response
                if (e instanceof SocketTimeoutException
                        || e.getCause() != null && e.getCause() instanceof SocketTimeoutException) {
                    responseStatusMessage = "Timeout waiting for response";

                    if (!tcpDispatcherProperties.isQueueOnResponseTimeout()) {
                        responseStatus = Status.ERROR;
                    }
                } else {
                    responseStatusMessage = "Error receiving response";
                }

                responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                        responseStatusMessage + ": " + e.getMessage(), e);
                logger.warn(responseStatusMessage + " (" + connectorProperties.getName() + " \""
                        + getDestinationName() + "\" on channel " + getChannelId() + ").", e);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                        message.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                        connectorProperties.getName(), responseStatusMessage + ".", e));
                eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                        getDestinationName(), ConnectionStatusEventType.FAILURE,
                        responseStatusMessage + " from " + SocketUtil.getInetAddress(socket)));

                closeSocketQuietly(socketKey);
            }
        } else {
            try {
                // MIRTH-2980: Since we're ignoring responses, flush out the socket's input stream so it doesn't continually grow
                socket.getInputStream().skip(socket.getInputStream().available());
            } catch (IOException e) {
                logger.warn("Error flushing socket input stream.", e);
            }

            // We're ignoring the response, so always return a successful response
            responseStatus = Status.SENT;
            responseStatusMessage = "Message successfully sent.";
        }

        if (tcpDispatcherProperties.isKeepConnectionOpen() && (getCurrentState() == DeployedState.STARTED
                || getCurrentState() == DeployedState.STARTING)) {
            if (sendTimeout > 0) {
                // Close the connection after the send timeout has been reached
                startThread(socketKey);
            }
        } else {
            // If keep connection open is false, then close the socket right now
            closeSocketQuietly(socketKey);
        }
    } catch (Throwable t) {
        disposeThreadQuietly(socketKey);
        closeSocketQuietly(socketKey);

        String monitorMessage = "Error sending message (" + SocketUtil.getLocalAddress(socket) + " -> "
                + SocketUtil.getInetAddress(socket) + "): " + t.getMessage();
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.FAILURE, monitorMessage));

        // If an exception occurred then close the socket, even if keep connection open is true
        responseStatusMessage = t.getClass().getSimpleName() + ": " + t.getMessage();
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), t.getMessage(), t);

        String logMessage = "Error sending message via TCP (" + connectorProperties.getName() + " \""
                + getDestinationName() + "\" on channel " + getChannelId() + ").";

        if (t instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        } else if (t instanceof ConnectException
                || t.getCause() != null && t.getCause() instanceof ConnectException) {
            if (isQueueEnabled()) {
                logger.warn(logMessage, t);
            } else {
                logger.error(logMessage, t);
            }
        } else {
            logger.debug(logMessage, t);
        }

        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), message.getMessageId(),
                ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(),
                "Error sending message via TCP.", t));
    } finally {
        eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE,
                SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket),
                (Boolean) null));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

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) {/*from   w  w w .ja  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  www  . ja  v a 2s. co m
    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;/*from  w w w.  j av  a  2  s.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;//from  www .  ja va2s. c o  m
        }
    }

    //        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

/**
 * ??/*  w  w w.  java 2  s  .  c  om*/
 *
 * @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 www.j a  v a 2 s .  c om*/
    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);
    }
}