public void run() { logger.info("Started GSN Controller on port " + gsnControllerPort); while (true) { try { Socket socket = mySocket.accept(); logger.debug("Opened connection on control socket."); socket.setSoTimeout(GSN_CONTROL_READ_TIMEOUT); // Only connections from localhost are allowed if (ValidityTools.isLocalhost(socket.getInetAddress().getHostAddress()) == false) { try { logger.warn( "Connection request from IP address >" + socket.getInetAddress().getHostAddress() + "< was denied."); socket.close(); } catch (IOException ioe) { // do nothing } continue; } new StopManager().start(); } catch (SocketTimeoutException e) { logger.debug("Connection timed out. Message was: " + e.getMessage()); } catch (IOException e) { logger.warn("Error while accepting control connection: " + e.getMessage()); } } }
public String waitForPassword(int timeout, String username) throws TimeoutException { while (!initiated) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } String password = ""; try { // send a message to the robot String response = robotSocketServer.sendMessageAndWaitForResponse("waitForPassword"); if (!response.startsWith("password is ")) { System.err.println( "waitForPassword RECEIVED MESSAGE DIFFERENT THAN \"password is ...\": " + response); System.exit(1); } password = response.substring(12, response.length()); System.out.println("Received: " + response + " Password is " + password); } catch (SocketTimeoutException ex) { System.err.println("waitForPassword EXCEPTION!"); ex.printStackTrace(); System.exit(1); } return password; }
public void run() { // Counter to wait for timeout 5 times int counter = 5; while (running) { try { byte[] buf = new byte[32]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(1000); // Wait for a message socket.receive(packet); // Clean the string (remove all the null characters) String message = new String(packet.getData()); int endoftext = message.indexOf("\0"); if (endoftext != -1) message = message.substring(0, endoftext); // If the message is different from the one sent if (!message.equals("requestIP")) { // Broadcast an intent with the message Intent answer = new Intent(Constants.UDP_ANSWER); answer.putExtra("message", message); sendBroadcast(answer); } } catch (SocketTimeoutException e) { // If the socket timed out, decrement the counter counter--; if (counter == 0) cancel(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
/* * Evento que se ejecuta cuando se invocó el servicio por medio de un * Intent. */ @Override protected void onHandleIntent(final Intent intent) { final ResultReceiver receiver = intent.getParcelableExtra("receiver"); final String command = intent.getStringExtra("command"); final String query = intent.getStringExtra("query"); final Bundle b = new Bundle(); try { if (command.equals(GET_PRODUCTS_CMD)) { getProducts(receiver, b, query); } } catch (SocketTimeoutException e) { Log.e(TAG, e.getMessage()); receiver.send(STATUS_CONNECTION_ERROR, b); } catch (JSONException e) { Log.e(TAG, e.getMessage()); receiver.send(STATUS_ERROR, b); } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage()); receiver.send(STATUS_ERROR, b); } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage()); receiver.send(STATUS_ILLEGAL_ARGUMENT, b); } catch (IOException e) { Log.e(TAG, e.getMessage()); receiver.send(STATUS_ERROR, b); } catch (Exception e) { Log.e(TAG, e.getMessage()); } // Es importante terminar el servicio lo antes posible. this.stopSelf(); }
/** * 下载文件 * * @param params 请求参数 * @param filepath 保存路径 */ public static File downloadFile(RequestParams params, String filepath) throws TaskException { // 设置断点续传 params.setAutoResume(true); params.setSaveFilePath(filepath); try { return x.http().getSync(params, File.class); } catch (SocketTimeoutException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (ConnectTimeoutException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (UnknownHostException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (IOException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (Throwable throwable) { TaskException taskException = null; if (throwable.getCause() instanceof TaskException) { taskException = (TaskException) throwable.getCause(); } else if (throwable instanceof TaskException) { taskException = (TaskException) throwable; } if (taskException != null) { throw taskException; } throw new TaskException( "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage()); } }
@Override protected DanmuFileData doInBackground(Void... voids) { Boolean isSuccessed = false; try { isSuccessed = NetWorkUtils.downLoadDanmuFile(chatId); } catch (SocketTimeoutException e) { e.printStackTrace(); return null; } L.e("网络请求成功" + isSuccessed); if (!isSuccessed) { return null; } File danmuFile = new File(Constant.DANMU_FILE_SAVE_PATH + chatId); if (!danmuFile.exists()) { return null; } L.e("文件解析成功"); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(danmuFile); } catch (FileNotFoundException e) { e.printStackTrace(); L.e("文件流读取失败"); return null; } L.e("文件流读取成功"); BiliDanmakuXMLParser biliDanmakuXMLParser = (BiliDanmakuXMLParser) DataUtils.parseXMLToDanmakuFile(fileInputStream, new BiliDanmakuXMLParser()); return biliDanmakuXMLParser.getDanmakuFileData(); }
public void receivePacket() { int buffLength = 256; byte[] buff = new byte[buffLength]; DatagramPacket packet = new DatagramPacket(buff, buffLength); try { socket.receive(packet); String message = new String(packet.getData(), 0, packet.getLength() - 2); System.out.println("receive message : " + message); if (message.indexOf(":") == -1) { return; } String[] fields = message.split(":"); long commandField = Long.parseLong(fields[4]); if ((commandField & IPMSG_ANSENTRY) != 0) { this.receiveAnswerEntry(fields, packet); } else if ((commandField & IPMSG_SENDMSG) != 0) { this.receiveMessage(fields, packet); } } catch (SocketTimeoutException ste) { ste.printStackTrace(); } catch (PortUnreachableException pue) { pue.printStackTrace(); } catch (IllegalBlockingModeException ibme) { ibme.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
public static byte[] post(String url, RequestEntity requestEntity) throws Exception { PostMethod method = new PostMethod(url); method.addRequestHeader("Connection", "Keep-Alive"); method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); method.setRequestEntity(requestEntity); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("httpCode=" + statusCode); return method.getResponseBody(); } return method.getResponseBody(); } catch (SocketTimeoutException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { method.releaseConnection(); } }
public static <T> T doPostSync(RequestParams params, Class<T> responseCls) throws TaskException { try { return x.http().postSync(params, responseCls); } catch (SocketTimeoutException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (ConnectTimeoutException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (UnknownHostException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (IOException e) { e.printStackTrace(); throw new TaskException(TaskException.TaskError.timeout.toString()); } catch (Throwable throwable) { TaskException taskException = null; if (throwable.getCause() instanceof TaskException) { taskException = (TaskException) throwable.getCause(); } else if (throwable instanceof TaskException) { taskException = (TaskException) throwable; } if (taskException != null) { throw taskException; } throw new TaskException( "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage()); } }
@GET @Path("/{imageStream}/tag/{imageStreamTag}") @Produces(MediaType.APPLICATION_JSON) public ImageStreamTag getImageStreamTag( @PathParam("namespace") String namespace, @PathParam("imageStream") String imageStream, @PathParam("imageStreamTag") String imageStreamTag) throws UnauthorizedException, ServerException { URL url; try { url = UriBuilder.fromPath(getTagUrlTemplate) .buildFromMap( ImmutableMap.of( "namespace", namespace, "imageStream", imageStream, "tag", imageStreamTag)) .toURL(); } catch (MalformedURLException e) { throw new ServerException("Unable to get image stream tag. " + e.getMessage(), e); } try { final String response = clientFactory.getHttpClient().get(url, IHttpClient.DEFAULT_READ_TIMEOUT); return DtoFactory.getInstance().createDtoFromJson(response, ImageStreamTag.class); } catch (SocketTimeoutException e) { throw new ServerException("Unable to get image stream tag. " + e.getMessage(), e); } }
private boolean checkConnectTimeout(HftpFileSystem fs, boolean ignoreReadTimeout) throws IOException { boolean timedout = false; List<HttpURLConnection> conns = new LinkedList<HttpURLConnection>(); try { // with a listen backlog of 1, should only have to make one connection // to trigger a connection timeout. however... linux doesn't honor the // socket's listen backlog so we have to try a bunch of times for (int n = 32; !timedout && n > 0; n--) { try { conns.add(fs.openConnection("/", "")); } catch (SocketTimeoutException ste) { String message = ste.getMessage(); // https will get a read timeout due to SSL negotiation, but // a normal http will not, so need to ignore SSL read timeouts // until a connect timeout occurs if (!(ignoreReadTimeout && message.equals("Read timed out"))) { timedout = true; assertEquals("connect timed out", message); } } } } finally { for (HttpURLConnection conn : conns) { conn.disconnect(); } } return timedout; }
/* (non-Javadoc) * @see botFramework.IBot#sendCommands() */ public void sendCommands() { String command; boolean success; while (!queuedCommands.isEmpty()) { command = queuedCommands.removeFirst(); success = send(command); if (success == false) { queuedCommands.addFirst(command); log.error("error sending command. will reconnect and retry"); sendErrorEvent("Bot.sendCommands", "problem", "Could not send - reconnecting"); reconnect("Write error!"); return; } } try { sender.flush(); } catch (SocketTimeoutException e) { log.error("socket timeout while flushing", e); sendErrorEvent("Bot.sendCommands", "SocketTimeoutException", e.getMessage()); } catch (IOException e) { log.error("ioexception while flushing", e); sendErrorEvent("Bot.sendCommands", "IOException", e.getMessage()); reconnect("Write error!"); } }
private boolean connectSPPMon() { if (state == ConnectionEvent.CONNECTION_PENDING) { ExpCoordinator.print( new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0); while (state == ConnectionEvent.CONNECTION_PENDING) { try { Thread.sleep(500); } catch (java.lang.InterruptedException e) { } } return (isConnected()); } state = ConnectionEvent.CONNECTION_PENDING; if (nonProxy != null) { try { nonProxy.connect(); } catch (UnknownHostException e) { boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage()); return rtn; } catch (SocketTimeoutException e) { boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage()); return rtn; } catch (IOException e) { boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage()); return rtn; } } return (isConnected()); }
/** * @param theUrl * @param conAttempts * @return * @throws IOException */ public int getResposeCode(String theUrl, int conAttempts) throws IOException { // throws IOException URL newUrl = new URL(theUrl); // These codes are returned to indicate either fault or not. int ERROR_CODE = 1000, OK_CODE = 0; HttpURLConnection huc = (HttpURLConnection) newUrl.openConnection(); huc.setRequestMethod("HEAD"); huc.setRequestProperty("User-Agent", userAgent); huc.setReadTimeout(2000); huc.connect(); try { return huc.getResponseCode(); } catch (java.net.SocketException e) { if (e.getMessage().equalsIgnoreCase("Unexpected end of file from server")) return OK_CODE; // link still valid so return a small positive int that isn't a http status // code else return ERROR_CODE; // error, return a large int that isn't included in any http status code } catch (java.net.SocketTimeoutException e) { if (e.getMessage().equalsIgnoreCase("Read timed out")) { if (conAttempts != MAX_CONNECTION_ATTEMPTS) return getResposeCode(theUrl, conAttempts + 1); else return ERROR_CODE; // ERROR return a large int that isn't included in any http status code } else return ERROR_CODE; } catch (IOException e) { e.printStackTrace(); return ERROR_CODE; // error, return a large int that isn't included in any http status code } }
public TicketsResponse checkTickets(TicketsRequest request) { String jsonResp = null; TicketsResponse response = null; TicketsResponseError responseError = null; try { jsonResp = sendRequest(request); try { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); response = mapper.readValue(jsonResp, TicketsResponse.class); } catch (JsonMappingException e) { // logger.error("Could not parse JSON, trying to parse an error. Original exception: ", // e); responseError = new ObjectMapper().readValue(jsonResp, TicketsResponseError.class); TicketsResponse invaildResponse = new TicketsResponse(); invaildResponse.setError(true); invaildResponse.setErrorDescription(responseError.getErrorDescription()); logger.error("UzGovUa error description: " + responseError.getErrorDescription()); return invaildResponse; } } catch (HttpException e) { e.printStackTrace(); logger.error(e.getMessage(), e); } catch (SocketTimeoutException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return response; }
public void testBlockingConnectTimesOut() throws Exception { AbstractNBSocket socket = udpSelectorProvider.openSocketChannel().socket(); try { socket.connect(new InetSocketAddress("127.0.0.1", 9999), 1000); fail("shouldn't have connected"); } catch (SocketTimeoutException iox) { assertEquals("operation timed out (1000)", iox.getMessage()); } }
/* (non-Javadoc) * @see botFramework.IBot#send(java.lang.String) */ public synchronized boolean send(String string) { try { sender.write(string); } catch (SocketTimeoutException e) { log.error("socket timeout while writing", e); sendErrorEvent("Bot.send", "SocketTimeoutException", e.getMessage()); return false; } catch (IOException e) { log.error("ioexception while writing", e); sendErrorEvent("Bot.send", "IOException", e.getMessage()); return false; } return true; }
protected String doInBackground(String... params) { Log.i(TAG, "doInBackground"); String respuesta = null; try { TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String IMEI = telephonyManager.getDeviceId(); String IMSI = telephonyManager.getSimSerialNumber(); String consulta; if (phone.getText().toString().equals("2")) { consulta = URLs.RESOURCE; } else consulta = SoapRequestMovistar.getResource(IMEI, IMSI, phone.getText().toString()); ArrayList<String> retorno = XMLParser.getReturnCode(consulta); code = Integer.valueOf(retorno.get(0)); if (code == 0) { respuesta = consulta; Log.i(TAG, retorno.get(1)); } else respuesta = retorno.get(1); return respuesta; } catch (HttpHostConnectException e2) { errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (HttpResponseException e3) { e3.printStackTrace(); errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (ParseException p) { p.printStackTrace(); errorMessage = "Error en la recepción de los datos. Por favor reintente"; return null; } catch (SocketTimeoutException s1) { s1.printStackTrace(); errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (ConnectTimeoutException et) { et.printStackTrace(); errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (Exception e1) { e1.printStackTrace(); errorMessage = "Ha ocurrido un error con la respuesta del servidor."; return null; } }
@Override public void onSocketTimeoutException(SocketTimeoutException e, Object arg1) { Message msg = new Message(); Bundle params = new Bundle(); params.putString("response", e.getMessage()); params.putString("title", "onSocketTimeoutException"); mHandler.sendMessage(msg); }
public JSONObject put(String path, ArrayList<NameValuePair> params) { JSONObject res = new JSONObject(); HttpPut httpPut = new HttpPut(host + ":" + port + path); try { httpPut.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response; response = httpClient.execute(httpPut); res = new JSONObject(EntityUtils.toString(response.getEntity())); } catch (ConnectTimeoutException c) { c.printStackTrace(); } catch (SocketTimeoutException s) { s.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return res; }
public JSONArray getArray(String path, ArrayList<NameValuePair> params) { JSONArray res = new JSONArray(); String paramString = URLEncodedUtils.format(params, "utf-8"); HttpGet httpGet = new HttpGet(host + ":" + port + path + "?" + paramString); HttpResponse response; try { response = httpClient.execute(httpGet); res = new JSONArray(EntityUtils.toString(response.getEntity())); } catch (ConnectTimeoutException c) { c.printStackTrace(); } catch (SocketTimeoutException s) { s.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return res; }
/** * 执行http get请求 * * @param url * @return HttpResult */ public HttpResult invoke(String url) { GetMethod get = null; HttpResult result = null; try { get = new GetMethod(url); getClient().executeMethod(get); int statusCode = get.getStatusCode(); String statusText = get.getStatusText(); result = new HttpResult(statusCode, statusText); if (statusCode == 200) { StringBuffer buf = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream())); String line; while ((line = br.readLine()) != null) { buf.append(line).append('\n'); } result.setBody(buf.toString()); } } catch (SocketTimeoutException e) { result = new HttpResult(408, "REQUEST TIMEOUT. " + e.getMessage()); } catch (java.net.ConnectException e) { result = new HttpResult(321, "Connection refused. " + e.getMessage()); } catch (Exception e) { LOG.error(e); result = new HttpResult(123, e.getMessage()); } finally { if (get != null) { try { // byte[] bytes = get.getResponseBody(); get.releaseConnection(); } catch (Exception e) { LOG.error(e); } } } return result; }
public synchronized boolean connect() { try { connection = new Socket((String) servers.get(currentServer), port); connection.setSoTimeout(10000); receiver = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); sender = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), encoding)); sender.write(irc.nick(myNick)); sender.write(irc.user(myNick, mode, realname)); sender.flush(); } catch (SocketTimeoutException e) { log.error("socket timeout while connecting", e); sendErrorEvent("Bot.connect", "SocketTimeoutException", e.getMessage()); return false; } catch (IOException e) { log.error("error while connecting", e); sendErrorEvent("Bot.connect", "IOException", e.getMessage()); return false; } return true; }
public void openTray(int trayNum) { while (!initiated) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } try { // send a message to the robot String response = robotSocketServer.sendMessageAndWaitForResponse("openTray " + trayNum); if (!response.startsWith("closedTray")) { System.err.println("openTray RECEIVED MESSAGE DIFFERENT THAN \"closedTray\": " + response); System.exit(1); } } catch (SocketTimeoutException ex) { System.err.println("openTray EXCEPTION!"); ex.printStackTrace(); System.exit(1); } }
public void read(URL url) throws Exception { URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection hc = ((HttpURLConnection) connection); // hc.setConnectTimeout(1000); // hc.setReadTimeout(6000); try { BufferedReader in = new BufferedReader(new InputStreamReader(hc.getInputStream())); String input; StringBuffer response = new StringBuffer(256); while ((input = in.readLine()) != null) { response.append(input + "\r"); System.out.println(input); } } catch (SocketTimeoutException x) { x.printStackTrace(); System.out.println(x.getClass().getName()); } } }
public void run() { OutputStream out = null; InputStream in = null; try { client.setSoTimeout(4000); while (true) { out = client.getOutputStream(); in = client.getInputStream(); byte[] temp = SocketUtil.readBytesFromStream(in); if (null != temp && temp.length > 0) { String proTypeStr = new String(temp); System.out.println("接收到客户端消息" + proTypeStr + "当前服务器端口是" + port); out.write(("success" + port).getBytes()); } } } catch (SocketTimeoutException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (client != null) { client.close(); } } catch (IOException e) { e.printStackTrace(); } } }
public void ringBuzzer() { while (!initiated) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } try { // send a message to the robot String response = robotSocketServer.sendMessageAndWaitForResponse("ringBuzzer"); if (!response.equals("ringBuzzer done")) { System.err.println( "ringBuzzer RECEIVED MESSAGE DIFFERENT THAN \"ringBuzzer done\": " + response); System.exit(1); } } catch (SocketTimeoutException ex) { System.err.println("ringBuzzer EXCEPTION!"); ex.printStackTrace(); System.exit(1); } }
@Override protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { if (localAddress != null) { socket.bind(localAddress); } boolean success = false; try { socket.connect(remoteAddress, config().getConnectTimeoutMillis()); activate(socket.getInputStream(), socket.getOutputStream()); success = true; } catch (SocketTimeoutException e) { ConnectTimeoutException cause = new ConnectTimeoutException("connection timed out: " + remoteAddress); cause.setStackTrace(e.getStackTrace()); throw cause; } finally { if (!success) { doClose(); } } }
@Test public void testHsftpSocketTimeout() throws Exception { Configuration conf = new Configuration(); ServerSocket socket = new ServerSocket(0, 1); URI uri = new URI( "hsftp", null, InetAddress.getByName(null).getHostAddress(), socket.getLocalPort(), null, null, null); boolean timedout = false; HsftpFileSystem fs = (HsftpFileSystem) FileSystem.get(uri, conf); try { HttpURLConnection conn = null; timedout = false; try { // this will consume the only slot in the backlog conn = fs.openConnection("/", ""); } catch (SocketTimeoutException ste) { // SSL expects a negotiation, so it will timeout on read, unlike hftp timedout = true; assertEquals("Read timed out", ste.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } assertTrue("ssl read connect timedout", timedout); assertTrue("connect timedout", checkConnectTimeout(fs, true)); } finally { fs.close(); } }
public void moveRobotToNextPoint() { while (!initiated) { try { Thread.sleep(100); } catch (InterruptedException ex) { } } try { // send a message to the robot String response = robotSocketServer.sendMessageAndWaitForResponse("move robot to next point"); if (!response.equals("next point found")) { System.err.println( "moveRobotToNextPoint RECEIVED MESSAGE DIFFERENT THAN \"next point found\": " + response); System.exit(1); } System.out.println("Robot arrived to the next point"); } catch (SocketTimeoutException ex) { System.err.println("moveRobotToNextPoint EXCEPTION!"); ex.printStackTrace(); System.exit(1); } }