List of usage examples for java.net Socket isConnected
public boolean isConnected()
From source file:org.wso2.mb.integration.tests.server.mgt.NewInstanceTestCase.java
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE }) @Test(groups = { "mb.server.startup" }) public void waitForPortTestCase() { boolean isPortOpen = false; long startTime = System.currentTimeMillis(); String hostName = "localhost"; while (!isPortOpen && (System.currentTimeMillis() - startTime) < TIMEOUT) { Socket socket = null; try {/*from w w w .ja va 2s. c o m*/ InetAddress address = InetAddress.getByName(hostName); socket = new Socket(address, 9445); isPortOpen = socket.isConnected(); } catch (IOException e) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } finally { try { if ((socket != null) && (socket.isConnected())) { socket.close(); } } catch (IOException e) { log.error("Can not close the socket which is used to check the server status ", e); } } } Assert.assertTrue(isPortOpen); }
From source file:Main.IrcBot.java
public void serverConnect() { try {//from ww w .ja va 2 s. c om Socket ircSocket = new Socket(this.hostName, this.portNumber); if (ircSocket.isConnected()) { final PrintWriter out = new PrintWriter(ircSocket.getOutputStream(), true); final BufferedReader in = new BufferedReader(new InputStreamReader(ircSocket.getInputStream())); final BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; String pass = "PASS *"; String nick = "NICK " + this.name; String user = "USER " + this.name + " 8 * :" + this.name; String channel = "JOIN " + this.channel; Timer channelChecker = new Timer(); out.println(pass); System.out.println("echo: " + in.readLine().toString()); out.println(nick); System.out.println("echo: " + in.readLine().toString()); out.println(user); System.out.println("echo: " + in.readLine().toString()); out.println(channel); channelChecker.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { String userIn = in.readLine().toString(); ; System.out.println(userIn); if (userIn.contains("PING")) { out.println("PONG hobana.freenode.net"); } if (userIn.contains("http://pastebin.com")) { //String[] urlCode = userIn.split("[http://pastebin.com]"); String url = "http://pastebin.com"; int indexStart = userIn.indexOf(url); int indexStop = userIn.indexOf(" ", indexStart); String urlCode = userIn.substring(indexStart, indexStop); String pasteBinId = urlCode.substring(urlCode.indexOf("/", 9) + 1, urlCode.length()); System.out.println(pasteBinId); IrcBot.postRequest(pasteBinId, out); } } catch (Exception j) { } } }, 100, 100); } else { System.out.println("There was an error connecting to the IRC server: " + this.hostName + " using port " + this.portNumber); } } catch (Exception e) { //System.out.println(e.getMessage()); } }
From source file:gridool.communication.transport.tcp.GridOioSharedClient.java
public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException { Socket socket; synchronized (clients) { socket = clients.get(sockAddr);/* ww w. j a v a 2 s . c om*/ if (socket == null) { socket = opneSocket(sockAddr); } else { if (!socket.isConnected()) { NetUtils.closeQuietly(socket); socket = opneSocket(sockAddr); } } } assert (socket != null); final byte[] b = GridUtils.toBytes(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending a message [" + msg.getMessageId() + " (" + b.length + " bytes)] to a node [" + sockAddr + "] using a socket [" + socket + ']'); } try { syncWrite(socket, b); } catch (IOException ioe) { final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr + ']'; LOG.error(errmsg, ioe); throw new GridException(errmsg, ioe); } catch (Throwable e) { LOG.fatal(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException("Unexpected exception was caused", e); } }
From source file:gridool.communication.transport.tcp.GridSharedClient.java
private Socket getSocket(SocketAddress sockAddr) throws GridException { Socket socket; synchronized (clients) { socket = clients.get(sockAddr);/*from w w w .ja v a2s .co m*/ if (socket == null) { socket = openSocket(sockAddr); } else { if (!socket.isConnected()) { NetUtils.closeQuietly(socket); socket = openSocket(sockAddr); clients.put(sockAddr, socket); } } } assert (socket != null); return socket; }
From source file:org.loggo.server.SimpleServerIT.java
@Test(timeout = 60 * 1000) public void sunnyDay() throws Exception { // no log files exist assertEquals(0, Iterators.size(conn.createScanner("logs", Authorizations.EMPTY).iterator())); // send a tcp message Socket s = new Socket("localhost", loggerPort); assertTrue(s.isConnected()); s.getOutputStream()/*from w w w. j a va 2s .co m*/ .write("localhost tester 2014-01-01 01:01:01,123 This is a test message\n\n".getBytes(UTF_8)); s.close(); // send a udp message DatagramSocket ds = new DatagramSocket(); String otherMessage = "localhost test2 2014-01-01 01:01:01,345 [INFO] This is a 2nd message"; byte[] otherMessageBytes = otherMessage.getBytes(UTF_8); InetSocketAddress dest = new InetSocketAddress("localhost", loggerPort); ds.send(new DatagramPacket(otherMessageBytes, otherMessageBytes.length, dest)); ds.close(); // wait for a flush sleepUninterruptibly(8, TimeUnit.SECONDS); // verify the messages are stored Scanner scanner = conn.createScanner("logs", Authorizations.EMPTY); assertEquals(2, Iterators.size(scanner.iterator())); Iterator<Entry<Key, Value>> iter = scanner.iterator(); Entry<Key, Value> next = iter.next(); assertEquals(next.getValue().toString(), "This is a test message"); assertEquals(next.getKey().getColumnQualifier().toString(), "tester\0localhost"); assertEquals(next.getKey().getColumnFamily().toString(), "UNKNOWN"); assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123")); next = iter.next(); assertEquals(next.getValue().toString(), "[INFO] This is a 2nd message"); assertEquals(next.getKey().getColumnQualifier().toString(), "test2\0localhost"); assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123")); assertFalse(iter.hasNext()); sleepUninterruptibly(30, TimeUnit.SECONDS); conn.tableOperations().deleteRows("logs", null, null); }
From source file:org.pircbotx.PircTestRunner.java
public PircTestRunner(Configuration.Builder config) throws IOException, IrcException { ACTIVE_INSTANCES.put(this, new RuntimeException("This forgot to call close")); InetAddress address = InetAddress.getByName("127.1.1.1"); Socket socket = mock(Socket.class); when(socket.isConnected()).thenReturn(true); when(socket.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0])); when(socket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); SocketFactory socketFactory = mock(SocketFactory.class); when(socketFactory.createSocket(eq(address), anyInt(), eq((InetAddress) null), eq(0))).thenReturn(socket); config.setSocketFactory(socketFactory); config.setListenerManager(/*from w w w .ja v a 2 s . c om*/ SequentialListenerManager.newDefault().updateExecutorAllInline().addListenerInline(new Listener() { final Logger log = LoggerFactory.getLogger(getClass()); @Override public void onEvent(Event event) { log.debug("Dispatched event " + event); eventQueue.addLast(event); } })); in = new FakeReader(); bot = new CapturedPircBotX(config.buildConfiguration()); bot.startBot(); }
From source file:org.wso2.mb.integration.tests.server.mgt.ProfileTestCase.java
@Test(groups = "mb.server.profiles", description = "Change the andes-virtualhosts and andes-config to rename the existing virtual host and start MB") public void testCassandraProfile() throws Exception { long startTime = System.currentTimeMillis(); boolean loginFailed = true; boolean isPortOpen = false; String hostName = "localhost"; while (!isPortOpen && (System.currentTimeMillis() - startTime) < TIMEOUT) { Socket socket = null; try {//from w w w. j a v a2 s . c o m InetAddress address = InetAddress.getByName(hostName); socket = new Socket(address, 9443); isPortOpen = socket.isConnected(); } catch (IOException e) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } finally { try { if ((socket != null) && (socket.isConnected())) { socket.close(); } } catch (IOException e) { log.error("Can not close the socket which is used to check the server status ", e); } } } Assert.assertTrue(isPortOpen); while (((System.currentTimeMillis() - startTime) < TIMEOUT) && loginFailed) { log.info("Waiting to login user..."); try { AuthenticatorClient authenticatorClient = new AuthenticatorClient( automationContext.getContextUrls().getBackEndUrl()); authenticatorClient.login(automationContext.getSuperTenant().getContextUser().getUserName(), automationContext.getSuperTenant().getContextUser().getPassword(), "127.0.0.1"); loginFailed = false; } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Login failed after server startup", e); } try { Thread.sleep(2000); } catch (InterruptedException ignored) { // Nothing to do } } } Assert.assertFalse(loginFailed); log.info("Successfully logged into MB."); }
From source file:org.pircbotx.output.OutputTest.java
@BeforeMethod public void botSetup() throws Exception { InetAddress localhost = InetAddress.getByName("127.1.1.1"); //Setup streams for bot inputLatch = new CountDownLatch(1); botOut = new ByteArrayOutputStream(); in = new ByteArrayInputStream("".getBytes()); Socket socket = mock(Socket.class); when(socket.isConnected()).thenReturn(true); when(socket.getInputStream()).thenReturn(in); when(socket.getOutputStream()).thenReturn(botOut); socketFactory = mock(SocketFactory.class); when(socketFactory.createSocket(localhost, 6667, null, 0)).thenReturn(socket); //Configure and connect bot bot = new PircBotX(TestUtils.generateConfigurationBuilder().setCapEnabled(true).setServerPassword(null) .setSocketFactory(socketFactory).buildConfiguration()); bot.startBot();/* w ww . ja v a2 s . c o m*/ //Make sure the bot is connected verify(socketFactory).createSocket(localhost, 6667, null, 0); //Setup useful vars aUser = TestUtils.generateTestUserSource(bot); aChannel = bot.getUserChannelDao().createChannel("#aChannel"); }
From source file:com.dbay.apns4j.impl.ApnsConnectionImpl.java
private boolean isSocketAlive(Socket socket) { if (socket != null && socket.isConnected()) { return true; }// w w w. ja va2 s . co m return false; }
From source file:io.aino.agents.core.AgentIntegrationTest.java
private boolean isReachable(String host, int port, int timeout) throws IOException { SocketAddress proxyAddress = new InetSocketAddress(host, port); Socket socket = new Socket(); try {/*www. j a v a 2 s. c om*/ socket.connect(proxyAddress, timeout); //System.out.println("Connected to: " + host + ":" + port); return socket.isConnected(); } catch (IOException e) { System.out.println("Could not connect to: " + host + ":" + port); return false; } finally { if (socket.isConnected()) { //System.out.println("Closing connection to: " + host + ":" + port); socket.close(); //System.out.println("Disconnected: " + host + ":" + port); } } }