List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:edu.virginia.iath.snac.helpers.GeoNamesHelper.java
/** * Connects to cheshire via a Socket on localhost, port 7010. * //from ww w. j a v a2 s . c om * @return True if connection was successful, false otherwise. */ public boolean connect() { try { cheshire = new Socket("localhost", 7010); out = new PrintWriter(cheshire.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(cheshire.getInputStream())); // Init cheshire out.println("init"); // Read the connection info off the buffer in.readLine(); return true; } catch (Exception e) { return false; } }
From source file:io.dacopancm.socketdcm.net.StreamSocket.java
public String getStreamFile() { String list = "false"; try {//from ww w .j a v a 2 s . com if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) { logger.log(Level.INFO, "get stream socket call"); sock = new Socket(ip, port); DataOutputStream dOut = new DataOutputStream(sock.getOutputStream()); DataInputStream dIn = new DataInputStream(sock.getInputStream()); dOut.writeUTF(ConectType.STREAM.name());//send stream type dOut.writeUTF("uncompressed");//send comprimido o no dOut.writeUTF(ConectType.GET_STREAM.toString()); //send type dOut.writeUTF(streamid); dOut.flush(); // Send off the data String rtspId = dIn.readUTF(); dOut.close(); logger.log(Level.INFO, "resp get stream file: {0}", rtspId); list = rtspId; } } catch (IOException ex) { HelperUtil.showErrorB("No se pudo establecer conexin"); logger.log(Level.INFO, "get stream file error no connect:{0}", ex.getMessage()); try { if (sock != null) { sock.close(); } } catch (IOException e) { } } return list; }
From source file:Main.IrcBot.java
public void serverConnect() { try {//from w ww. j av a 2 s .com 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:com.liveramp.hank.test.ZkTestCase.java
private static boolean waitForServerUp(int port, long timeout) { long start = System.currentTimeMillis(); while (true) { try {/*from w w w .j a v a2 s .co m*/ Socket sock = new Socket("localhost", port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); Reader isr = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isr); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server localhost:" + port + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; }
From source file:com.linkedin.databus2.test.TestUtil.java
/** * Checks if a server is running on a given host and port * @param host the server host//from w w w. ja v a 2 s . com * @param port the server port * @param log logger for diagnostic messages (can be null) * @return true if successful * @throws IOException */ public static boolean checkServerRunning(String host, int port, Logger log, boolean logError) { boolean success = false; try { Socket socket = new Socket(host, port); log.info("host=" + host + " port=" + port); log.info("Socket Info:" + socket.toString()); log.info("IsConnected=" + socket.isConnected() + " isClosed=" + socket.isClosed() + " isBound=" + socket.isBound()); success = socket.isConnected(); socket.close(); } catch (ConnectException ce) { if (null != log) log.error("Fail to connect to port:" + port); if (logError && null != log) log.error("Connect error", ce); success = false; } catch (IOException e) { if (logError && null != log) log.error("connect error", e); } catch (RuntimeException e) { if (logError && null != log) log.error("runtime error", e); } return success; }
From source file:barrysw19.calculon.fics.FICSInterface.java
public void connect() throws IOException { connection = new Socket("freechess.org", 23); doLogin();//from w w w . j av a 2s .co m BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); out = new PrintStream(connection.getOutputStream()); send("set style 12"); send("iset movecase 1"); send("iset block 1"); blockOn = true; setStatus(); if (ficsConfig.isReseek()) { reseek(); } Runnable keepAlive = () -> { while (alive) { send("date"); try { Thread.sleep(60000 * 15); } catch (InterruptedException ignored) { } } }; Thread keepAliveThread = new Thread(keepAlive); keepAliveThread.start(); String line; try { while ((line = reader.readLine()) != null) { // if (line.trim().length() == 0) { // continue; // } log.info("Recv: '" + line + "'"); for (ConnectionListener listener : listeners) { listener.message(line); } } } finally { alive = false; try { reader.close(); out.close(); } catch (Exception ignored) { } } }
From source file:fit.FitServer.java
private void establishConnection(String httpRequest) throws IOException { socket = new Socket(host, port); output = socket.getOutputStream();/*from www .j a v a 2s .co m*/ input = new StreamReader(socket.getInputStream()); byte[] bytes; try { bytes = httpRequest.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new ImpossibleException("UTF-8 is a supported encoding", e); } output.write(bytes); output.flush(); logger.debug("http request sent"); }
From source file:net.ab0oo.aprs.clients.PGClient.java
public void connectAndParse() { String sentence;//from ww w . ja va 2 s. c o m String modifiedSentence = ""; try { clientSocket = new Socket(server, port); outToServer = new DataOutputStream(clientSocket.getOutputStream()); inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } catch (UnknownHostException uhex) { System.err.println("Unknown hostname " + server + ": " + uhex); System.exit(1); } catch (IOException ioex) { System.err.println("Unable to use TCP/IP socket to APRS-IS server: " + ioex); System.exit(1); } try { sentence = "user " + callsign + " pass " + aprsPass + " vers test 1.0 " + aprsFilter; outToServer.writeBytes(sentence + '\n'); } catch (IOException ioex) { System.err.println("Unable to use TCP/IP socket to APRS-IS server: " + ioex); } APRSPacket packet; while (true) { try { modifiedSentence = inFromServer.readLine(); if (!modifiedSentence.startsWith("#")) { packet = Parser.parse(modifiedSentence); processPacket(packet); } } catch (Exception ex) { System.err.println("Exception during Network read: " + ex); ex.printStackTrace(); System.err.println("Culprit was " + modifiedSentence); } } }
From source file:dk.netarkivet.viewerproxy.WebProxyTester.java
/** * Test the general integration of the WebProxy access through the running Jetty true: *///from w ww. ja v a 2 s. com @Test public void testJettyIntegration() throws Exception { TestURIResolver uriResolver = new TestURIResolver(); proxy = new WebProxy(uriResolver); try { new Socket(InetAddress.getLocalHost(), httpPort); } catch (IOException e) { fail("Port not in use after starting server"); } // GET request HttpClient client = new HttpClient(); HostConfiguration hc = new HostConfiguration(); String hostName = SystemUtils.getLocalHostName(); hc.setProxy(hostName, httpPort); client.setHostConfiguration(hc); GetMethod get = new GetMethod("http://foo.bar/"); client.executeMethod(get); assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString()); get.releaseConnection(); // POST request PostMethod post = new PostMethod("http://foo2.bar/"); post.addParameter("a", "x"); post.addParameter("a", "y"); client.executeMethod(post); // Check request received by URIResolver assertEquals("URI resolver lookup should be called.", 2, uriResolver.lookupCount); assertEquals("URI resolver lookup should be called with right URI.", new URI("http://foo2.bar/"), uriResolver.lookupRequestArgument); assertEquals("Posted parameter should be received.", 1, uriResolver.lookupRequestParameteres.size()); assertNotNull("Posted parameter should be received.", uriResolver.lookupRequestParameteres.get("a")); assertEquals("Posted parameter should be received.", 2, uriResolver.lookupRequestParameteres.get("a").length); assertEquals("Posted parameter should be received.", "x", uriResolver.lookupRequestParameteres.get("a")[0]); assertEquals("Posted parameter should be received.", "y", uriResolver.lookupRequestParameteres.get("a")[1]); assertEquals("Status code should be what URI resolver gives", 242, post.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", post.getResponseBodyAsString()); post.releaseConnection(); // Request with parameter and portno get = new GetMethod("http://foo2.bar:8090/?baz=boo"); client.executeMethod(get); // Check request received by URIResolver assertEquals("URI resolver lookup should be called.", 3, uriResolver.lookupCount); assertEquals("URI resolver 2 lookup should be called with right URI.", new URI("http://foo2.bar:8090/?baz=boo"), uriResolver.lookupRequestArgument); assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString()); get.releaseConnection(); }
From source file:com.alexkli.jhb.Worker.java
@Override public void run() { try {//from ww w. ja v a 2 s . c o m while (true) { long start = System.nanoTime(); QueueItem<HttpRequestBase> item = queue.take(); idleAvg.add(System.nanoTime() - start); if (item.isPoisonPill()) { return; } HttpRequestBase request = item.getRequest(); if ("java".equals(config.client)) { System.setProperty("http.keepAlive", "false"); item.sent(); try { HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString()) .openConnection(); http.setConnectTimeout(5000); http.setReadTimeout(5000); int statusCode = http.getResponseCode(); consumeAndCloseStream(http.getInputStream()); if (statusCode == 200) { item.done(); } else { item.failed(); } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); e.printStackTrace(); // System.exit(2); item.failed(); } } else if ("ahc".equals(config.client)) { try { item.sent(); try (CloseableHttpResponse response = httpClient.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { item.done(); } else { item.failed(); } } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); item.failed(); } } else if ("fast".equals(config.client)) { try { URI uri = request.getURI(); item.sent(); InetAddress addr = InetAddress.getByName(uri.getHost()); Socket socket = new Socket(addr, uri.getPort()); PrintWriter out = new PrintWriter(socket.getOutputStream()); // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort()); out.println("Connection: Close"); out.println(); out.flush(); // read the response consumeAndCloseStream(socket.getInputStream()); // boolean loop = true; // StringBuilder sb = new StringBuilder(8096); // while (loop) { // if (in.ready()) { // int i = 0; // while (i != -1) { // i = in.read(); // sb.append((char) i); // } // loop = false; // } // } item.done(); socket.close(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } else if ("nio".equals(config.client)) { URI uri = request.getURI(); item.sent(); String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n" + "Connection: Close\n\n"; try { InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort()); SocketChannel channel = SocketChannel.open(); channel.socket().setSoTimeout(5000); channel.connect(addr); ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes()); channel.write(msg); msg.clear(); ByteBuffer buf = ByteBuffer.allocate(1024); int count; while ((count = channel.read(buf)) != -1) { buf.flip(); byte[] bytes = new byte[count]; buf.get(bytes); buf.clear(); } channel.close(); item.done(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } } } catch (InterruptedException e) { System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage()); } }