List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java
/** * @throws Exception if a GNS error occurs * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy() *//* w w w. ja va 2 s .co m*/ @Override public List<InetSocketAddress> getNewProxy() throws Exception { // Lookup for active location service GUIDs final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); final GuidEntry guidEntry = gnsCredentials.getGuidEntry(); JSONArray guids; try { guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry); } catch (Exception e) { throw new GnsException("Could not find active location services (" + e + ")"); } // Try every location proxy in the list until one works for (int i = 0; i < guids.length(); i++) { // Retrieve the location service IP and connect to it String locationGuid = guids.getString(i); String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry) .getString(0); logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies"); // Location IP is stored as host:port StringTokenizer st = new StringTokenizer(locationIP, ":"); try { // Protocol is send the number of desired proxies and receive strings // containing proxy IP:port Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken())); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); oos.writeInt(numProxies); oos.flush(); List<InetSocketAddress> result = new LinkedList<InetSocketAddress>(); while (!s.isClosed() && result.size() < numProxies) { String proxyIP = ois.readUTF(); StringTokenizer stp = new StringTokenizer(proxyIP, ":"); result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken()))); } if (!s.isClosed()) // We receive all the proxies we need, just close the // socket s.close(); return result; } catch (Exception e) { logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")"); } } throw new GnsException("Could not find any location service to provide a geolocated proxy"); }
From source file:SocketApplet.java
/** Initialize the GUI nicely. */ public void init() { Label aLabel;//w ww.j a v a2 s .c o m setLayout(new GridBagLayout()); int LOGO_COL = 1; int LABEL_COL = 2; int TEXT_COL = 3; int BUTTON_COL = 1; GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 100.0; gbc.weighty = 100.0; gbc.gridx = LABEL_COL; gbc.gridy = 0; gbc.anchor = GridBagConstraints.EAST; add(aLabel = new Label("Name:", Label.CENTER), gbc); gbc.anchor = GridBagConstraints.CENTER; gbc.gridx = TEXT_COL; gbc.gridy = 0; add(nameTF = new TextField(10), gbc); gbc.gridx = LABEL_COL; gbc.gridy = 1; gbc.anchor = GridBagConstraints.EAST; add(aLabel = new Label("Password:", Label.CENTER), gbc); gbc.anchor = GridBagConstraints.CENTER; gbc.gridx = TEXT_COL; gbc.gridy = 1; add(passTF = new TextField(10), gbc); passTF.setEchoChar('*'); gbc.gridx = LABEL_COL; gbc.gridy = 2; gbc.anchor = GridBagConstraints.EAST; add(aLabel = new Label("Domain:", Label.CENTER), gbc); gbc.anchor = GridBagConstraints.CENTER; gbc.gridx = TEXT_COL; gbc.gridy = 2; add(domainTF = new TextField(10), gbc); sendButton = new Button("Send data"); gbc.gridx = BUTTON_COL; gbc.gridy = 3; gbc.gridwidth = 3; add(sendButton, gbc); whence = getCodeBase(); // Now the action begins... sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { String name = nameTF.getText(); if (name.length() == 0) { showStatus("Name required"); return; } String domain = domainTF.getText(); if (domain.length() == 0) { showStatus("Domain required"); return; } showStatus("Connecting to host " + whence.getHost() + " as " + nameTF.getText()); try { Socket s = new Socket(getCodeBase().getHost(), 3333); PrintWriter pf = new PrintWriter(s.getOutputStream(), true); // send login name pf.println(nameTF.getText()); // passwd pf.println(passTF.getText()); // and domain pf.println(domainTF.getText()); BufferedReader is = new BufferedReader(new InputStreamReader(s.getInputStream())); String response = is.readLine(); showStatus(response); } catch (IOException e) { showStatus("ERROR: " + e.getMessage()); } } }); }
From source file:com.liferay.sync.engine.util.SyncSystemTestUtil.java
protected static boolean isPortInUse(int port) { try {//from ww w .j a va 2 s . c om Socket socket = new Socket("localhost", port); socket.close(); return true; } catch (IOException ioe) { return false; } }
From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java
/** * Test the we can ping the agent./*from w w w . j a v a 2 s .c o m*/ * * @throws Exception * When the test failed. */ @Test public void testPing() throws Exception { final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent(); // give the agent some time to open the port Thread.sleep(100); final Socket socket = new Socket(InetAddress.getLocalHost(), org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT); final Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("agent.ping\n"); out.flush(); final InputStream in = socket.getInputStream(); final byte[] buffer = new byte[1024]; final int read = in.read(buffer); assertEquals(14, read); assertEquals('Z', buffer[0]); assertEquals('B', buffer[1]); assertEquals('X', buffer[2]); assertEquals('D', buffer[3]); assertEquals('1', buffer[13]); // we'll take the rest for granted... socket.close(); agent.stop(); }
From source file:de.xwic.appkit.core.cluster.impl.OutboundChannel.java
/** * @throws IOException // w w w . j av a 2s. c o m * @throws UnknownHostException * */ private void openConnection() throws UnknownHostException, IOException { socket = new Socket(nodeAddress.getHostname(), nodeAddress.getPort()); // socket.setSoTimeout(SOCKET_TIMEOUT); out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream(socket.getInputStream()); }
From source file:com.googlecode.jmxtrans.model.output.SensuWriter.java
private void writeToSensu(Server server, Query query, List<Result> results) { try (Socket socketConnection = new Socket(host, 3030)) { serialize(server, query, results, socketConnection.getOutputStream()); } catch (Exception e) { logger.warn("Failure to send result to Sensu server '{}'", host, e); }// w ww .j a v a2 s . c o m }
From source file:com.apporiented.hermesftp.client.FtpTestClient.java
/** * Opening a connection to the FTP server. * //from ww w. j ava 2s. co m * @param svr The server name. If null is passed, the local machine is used. * @param user The user name. * @param pass The user password. * @param port FTP port. * @throws IOException Error on connection. */ public void openConnection(String svr, String user, String pass, int port) throws IOException { this.server = svr; if (server == null || server.startsWith("127.0.0.")) { this.server = NetUtils.getMachineAddress(true).getHostAddress(); } serverSocket = new Socket(server, port); in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream())); out = new PrintWriter(serverSocket.getOutputStream(), true); getResponse(); sendAndReceive("USER " + user); sendAndReceive("PASS " + pass); }
From source file:UseFactory.java
public Socket createSocket(String host, int port) throws IOException, UnknownHostException { System.out.println("[creating a custom socket (method 1)]"); return new Socket(host, port); }//from w w w .j ava 2s . com
From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java
@Test public void testMultipleMessages() throws IOException { SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder() .withConfig(//from www .ja v a 2s . com SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build()) .withConnectorFactory(TcpConnectorFactory.Builder.builder() .withConnectedSocketTask(new TcpConnectTestHandler()).build()) .build(); simpleNbServer.start(); String message1 = "this is message1"; String message2 = "this is message2"; try { Socket socket = new Socket("localhost", 1111); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); // message1 out.write((message1 + '\n' + message2 + '\n').getBytes(StandardCharsets.UTF_8)); String messageRead1 = reader.readLine(); Assert.assertEquals(message1, messageRead1); String messageRead2 = reader.readLine(); Assert.assertEquals(message2, messageRead2); // quit out.write("quit\n".getBytes(StandardCharsets.UTF_8)); String finalMessage = reader.readLine(); Assert.assertNull(finalMessage); } finally { simpleNbServer.shutdown(); } }
From source file:com.atlassian.theplugin.commons.ssl.PluginSSLProtocolSocketFactory.java
/** * Copied from AXIS source code,//from w w w . j a v a 2 s . co m * original @author Davanum Srinivas (dims@yahoo.com) * THIS CODE STILL HAS DEPENDENCIES ON sun.* and com.sun.* */ public Socket create(final String host, final int port, final StringBuffer otherHeaders, final BooleanHolder useFullURL) throws Exception { PluginConfiguration config = ConfigurationFactory.getConfiguration(); int sslPort = port; if (port == -1) { sslPort = EasySSLProtocolSocketFactory.SSL_PORT; } boolean hostInNonProxyList = false; TransportClientProperties tcp = TransportClientPropertiesFactory.create("https"); if (tcp instanceof DefaultHTTPSTransportClientProperties) { hostInNonProxyList = ((DefaultHTTPSTransportClientProperties) tcp).getNonProxyHosts().contains("host"); } //boolean hostInNonProxyList = super.isHostInNonPxyList(host, tcp.getNonProxyHosts()); Socket sslSocket; if (!config.getGeneralConfigurationData().getUseIdeaProxySettings() || hostInNonProxyList || tcp.getProxyHost().length() == 0) { // direct SSL connection sslSocket = super.createSocket(host, sslPort); } else { int tunnelPort = (tcp.getProxyPort().length() != 0) ? Integer.parseInt(tcp.getProxyPort()) : DEFAULT_PROXY_PORT; if (tunnelPort < 0) { tunnelPort = DEFAULT_PROXY_PORT; } // Create the regular socket connection to the proxy //Socket l = new Socket(new InetAddressImpl(tcp.getProxyHost()), tunnelPort); Socket tunnel = new Socket(InetAddress.getByName(tcp.getProxyHost()), tunnelPort); // The tunnel handshake method (condensed and made reflexive) OutputStream tunnelOutputStream = tunnel.getOutputStream(); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(tunnelOutputStream))); // More secure version... engage later? // PasswordAuthentication pa = // Authenticator.requestPasswordAuthentication( // InetAddress.getByName(tunnelHost), // tunnelPort, "SOCK", "Proxy","HTTP"); // if(pa == null){ // printDebug("No Authenticator set."); // }else{ // printDebug("Using Authenticator."); // tunnelUser = pa.getUserName(); // tunnelPassword = new String(pa.getPassword()); // } out.print("CONNECT " + host + ":" + sslPort + " HTTP/1.0\r\n" + "User-Agent: AxisClient"); if (tcp.getProxyUser().length() != 0 && tcp.getProxyPassword().length() != 0) { // add basic authentication header for the proxy String encodedPassword = XMLUtils .base64encode((tcp.getProxyUser() + ":" + tcp.getProxyPassword()).getBytes()); out.print("\nProxy-Authorization: Basic " + encodedPassword); } out.print("\nContent-Length: 0"); out.print("\nPragma: no-cache"); out.print("\r\n\r\n"); out.flush(); InputStream tunnelInputStream = tunnel.getInputStream(); if (logger != null) { logger.debug( Messages.getMessage("isNull00", "tunnelInputStream", "" + (tunnelInputStream == null))); } String replyStr = ""; // Make sure to read all the response from the proxy to prevent SSL negotiation failure // Response message terminated by two sequential newlines int newlinesSeen = 0; boolean headerDone = false; /* Done on first newline */ while (newlinesSeen < 2) { int i = tunnelInputStream.read(); if (i < 0) { throw new IOException("Unexpected EOF from proxy"); } if (i == '\n') { headerDone = true; ++newlinesSeen; } else if (i != '\r') { newlinesSeen = 0; if (!headerDone) { replyStr += String.valueOf((char) i); } } } if (!StringUtils.startsWithIgnoreWhitespaces("HTTP/1.0 200", replyStr) && !StringUtils.startsWithIgnoreWhitespaces("HTTP/1.1 200", replyStr)) { throw new IOException(Messages.getMessage("cantTunnel00", new String[] { tcp.getProxyHost(), "" + tunnelPort, replyStr })); } // End of condensed reflective tunnel handshake method sslSocket = super.createSocket(tunnel, host, port, true); if (logger != null) { logger.debug(Messages.getMessage("setupTunnel00", tcp.getProxyHost(), "" + tunnelPort)); } } ((SSLSocket) sslSocket).startHandshake(); if (logger != null) { logger.debug(Messages.getMessage("createdSSL00")); } return sslSocket; }