List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String RegisterTheDevice(String sSrvr, String sPort, String sData) { String sRet = ""; String line = ""; // Debug.waitForDebugger(); if (sSrvr != null && sPort != null && sData != null) { try {//from w w w .j av a2s .co m int nPort = Integer.parseInt(sPort); Socket socket = new Socket(sSrvr, nPort); PrintWriter out = new PrintWriter(socket.getOutputStream(), false); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println(sData); if (out.checkError() == false) { socket.setSoTimeout(30000); while (socket.isInputShutdown() == false) { line = in.readLine(); if (line != null) { line = line.toLowerCase(); sRet += line; // ok means we're done if (line.contains("ok")) break; } else { // end of stream reached break; } } } out.close(); in.close(); socket.close(); } catch (NumberFormatException e) { sRet += "reg NumberFormatException thrown [" + e.getLocalizedMessage() + "]"; e.printStackTrace(); } catch (UnknownHostException e) { sRet += "reg UnknownHostException thrown [" + e.getLocalizedMessage() + "]"; e.printStackTrace(); } catch (IOException e) { sRet += "reg IOException thrown [" + e.getLocalizedMessage() + "]"; e.printStackTrace(); } } return (sRet); }
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 ww w .j av a 2 s.co 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:Tcpbw100.java
public boolean test_mid(Protocol ctl) throws IOException { byte buff[] = new byte[8192]; Message msg = new Message(); if ((tests & TEST_MID) == TEST_MID) { /* now look for middleboxes (firewalls, NATs, and other boxes that * muck with TCP's end-to-end priciples *///w w w . j a v a2 s . c om showStatus(messages.getString("middleboxTest")); results.append(messages.getString("checkingMiddleboxes") + " "); statistics.append(messages.getString("checkingMiddleboxes") + " "); emailText = messages.getString("checkingMiddleboxes") + " "; pub_status = "checkingMiddleboxes"; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_PREPARE) { errmsg = messages.getString("mboxWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } int midport = Integer.parseInt(new String(msg.body)); Socket in2Socket = null; try { in2Socket = new Socket(host, midport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); errmsg = messages.getString("unknownServer") + "\n"; return true; } catch (IOException e) { System.err.println("Couldn't perform middlebox testing to: " + host); errmsg = messages.getString("middleboxFail") + "\n"; return true; } InputStream srvin2 = in2Socket.getInputStream(); OutputStream srvout2 = in2Socket.getOutputStream(); int largewin = 128 * 1024; in2Socket.setSoTimeout(6500); int bytes = 0; int inlth; t = System.currentTimeMillis(); pub_TimeStamp = new Date(); try { while ((inlth = srvin2.read(buff, 0, buff.length)) > 0) { bytes += inlth; pub_bytes = bytes; if ((System.currentTimeMillis() - t) > 5500) break; } } catch (IOException e) { } t = System.currentTimeMillis() - t; System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs"); s2cspd = ((8.0 * bytes) / 1000) / t; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_MSG) { errmsg = messages.getString("mboxWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } tmpstr2 = new String(msg.body); String tmpstr4 = Double.toString(s2cspd * 1000); System.out.println("Sending '" + tmpstr4 + "' back to server"); ctl.send_msg(TEST_MSG, tmpstr4.getBytes()); try { tmpstr2 += in2Socket.getInetAddress() + ";"; } catch (SecurityException e) { System.err.println("Unable to obtain Servers IP addresses: using " + host); errmsg = "getInetAddress() called failed\n"; tmpstr2 += host + ";"; results.append(messages.getString("lookupError") + "\n"); } System.err.println("calling in2Socket.getLocalAddress()"); try { tmpstr2 += in2Socket.getLocalAddress() + ";"; } catch (SecurityException e) { System.err.println("Unable to obtain local IP address: using 127.0.0.1"); errmsg = "getLocalAddress() call failed\n"; tmpstr2 += "127.0.0.1;"; } srvin2.close(); srvout2.close(); in2Socket.close(); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_FINALIZE) { errmsg = messages.getString("mboxWrongMessage"); if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } results.append(messages.getString("done") + "\n"); statistics.append(messages.getString("done") + "\n"); emailText += messages.getString("done") + "\n%0A"; } return false; }
From source file:org.eredlab.g4.ccl.net.ftp.FTPClient.java
/** * Establishes a data connection with the FTP server, returning * a Socket for the connection if successful. If a restart * offset has been set with {@link #setRestartOffset(long)}, * a REST command is issued to the server with the offset as * an argument before establishing the data connection. Active * mode connections also cause a local PORT command to be issued. * <p>/*from www. ja va 2 s.c om*/ * @param command The text representation of the FTP command to send. * @param arg The arguments to the FTP command. If this parameter is * set to null, then the command is sent with no argument. * @return A Socket corresponding to the established data connection. * Null is returned if an FTP protocol error is reported at * any point during the establishment and initialization of * the connection. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. */ protected Socket _openDataConnection_(int command, String arg) throws IOException { Socket socket; if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) return null; if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) { ServerSocket server; server = _socketFactory_.createServerSocket(0, 1, getLocalAddress()); if (!FTPReply.isPositiveCompletion(port(getLocalAddress(), server.getLocalPort()))) { server.close(); return null; } if ((__restartOffset > 0) && !restart(__restartOffset)) { server.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { server.close(); return null; } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) server.setSoTimeout(__dataTimeout); socket = server.accept(); server.close(); } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) return null; __parsePassiveModeReply((String) _replyLines.elementAt(0)); socket = _socketFactory_.createSocket(__passiveHost, __passivePort); if ((__restartOffset > 0) && !restart(__restartOffset)) { socket.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } } if (__remoteVerificationEnabled && !verifyRemote(socket)) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); socket.close(); throw new IOException("Host attempting data connection " + host1.getHostAddress() + " is not same as server " + host2.getHostAddress()); } if (__dataTimeout >= 0) socket.setSoTimeout(__dataTimeout); return socket; }
From source file:Tcpbw100.java
public boolean test_s2c(Protocol ctl, Socket ctlSocket) throws IOException { byte buff[] = new byte[8192]; Message msg = new Message(); if ((tests & TEST_S2C) == TEST_S2C) { showStatus(messages.getString("inboundTest")); results.append(messages.getString("runningInboundTest") + " "); statistics.append(messages.getString("runningInboundTest") + " "); emailText += messages.getString("runningInboundTest") + " "; pub_status = "runningInboundTest"; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; }/*w w w .ja v a2 s.co m*/ if (msg.type != TEST_PREPARE) { errmsg = messages.getString("inboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } int s2cport = Integer.parseInt(new String(msg.body)); Socket inSocket; try { inSocket = new Socket(host, s2cport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); errmsg = "unknown server\n"; return true; } catch (IOException e) { System.err.println("Couldn't get 3rd connection to: " + host); errmsg = "Server Failed while receiving data\n"; return true; } InputStream srvin = inSocket.getInputStream(); int bytes = 0; int inlth; // wait here for signal from server application if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("unknownServer") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_START) { errmsg = messages.getString("serverFail") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } inSocket.setSoTimeout(15000); t = System.currentTimeMillis(); pub_time = t; try { while ((inlth = srvin.read(buff, 0, buff.length)) > 0) { bytes += inlth; pub_bytes = bytes; if ((System.currentTimeMillis() - t) > 14500) break; } } catch (IOException e) { } t = System.currentTimeMillis() - t; System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs"); s2cspd = ((8.0 * bytes) / 1000) / t; /* receive the s2cspd from the server */ if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_MSG) { errmsg = messages.getString("inboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } try { String tmpstr3 = new String(msg.body); int k1 = tmpstr3.indexOf(" "); int k2 = tmpstr3.substring(k1 + 1).indexOf(" "); ss2cspd = Double.parseDouble(tmpstr3.substring(0, k1)) / 1000.0; ssndqueue = Integer.parseInt(tmpstr3.substring(k1 + 1).substring(0, k2)); sbytes = Double.parseDouble(tmpstr3.substring(k1 + 1).substring(k2 + 1)); } catch (Exception e) { e.printStackTrace(); errmsg = messages.getString("inboundWrongMessage") + "\n"; return true; } if (s2cspd < 1.0) { results.append(prtdbl(s2cspd * 1000) + "kb/s\n"); statistics.append(prtdbl(s2cspd * 1000) + "kb/s\n"); emailText += prtdbl(s2cspd * 1000) + "kb/s\n%0A"; } else { results.append(prtdbl(s2cspd) + "Mb/s\n"); statistics.append(prtdbl(s2cspd) + "Mb/s\n"); emailText += prtdbl(s2cspd) + "Mb/s\n%0A"; } // Expose download speed to JavaScript clients pub_s2cspd = s2cspd; dnlLbl.setText(String.format(padding + "%.3f Mbps", s2cspd)); pub_status = "done"; srvin.close(); inSocket.close(); buff = Double.toString(s2cspd * 1000).getBytes(); String tmpstr4 = new String(buff, 0, buff.length); System.out.println("Sending '" + tmpstr4 + "' back to server"); ctl.send_msg(TEST_MSG, buff); /* get web100 variables from server */ tmpstr = ""; int i = 0; // Try setting a 5 second timer here to break out if the read fails. ctlSocket.setSoTimeout(5000); try { for (;;) { if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type == TEST_FINALIZE) { break; } if (msg.type != TEST_MSG) { errmsg = messages.getString("inboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } tmpstr += new String(msg.body); i++; } } catch (IOException e) { } ctlSocket.setSoTimeout(0); } pub_status = "done"; return false; }
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);/*ww w.j a v 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;//from w w w .j a v a 2s .co 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 w ww .ja v a 2s. 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 .j a v a 2 s . c o 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;//w w w . j a va 2s . 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); } }