List of usage examples for java.net Socket getInetAddress
public InetAddress getInetAddress()
From source file:com.googlecode.jcimd.DummyCimdServer.java
public void start() throws IOException { this.serverSocket = new ServerSocket(this.port); if (this.logger.isInfoEnabled()) { this.logger.info("Listening on port " + this.port); }/* w w w . j a va2s .c om*/ Runnable listener = new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { try { Socket socket = serverSocket.accept(); socket.setSoTimeout(2000); if (logger.isInfoEnabled()) { logger.info("Starting session with " + socket.getInetAddress().getHostAddress() + ":" + socket.hashCode()); } DummyCimdServer.Session session = new Session(socket); //List<Session> sessions = ...; //sessions.add(session); new Thread(session).start(); } catch (SocketException e) { // Ignore, as this was due to #stop } } } catch (IOException e) { throw new RuntimeException(e); } } }; this.thread = new Thread(listener, this.getClass().getName() + "-listener"); this.thread.start(); }
From source file:com.yahoo.pulsar.testclient.LoadSimulationClient.java
public void run() throws Exception { final ServerSocket serverSocket = new ServerSocket(port); while (true) { // Technically, two controllers can be connected simultaneously, but // non-sequential handling of commands // has not been tested or considered and is not recommended. log.info("Listening for controller command..."); final Socket socket = serverSocket.accept(); log.info("Connected to {}\n", socket.getInetAddress().getHostName()); executor.submit(() -> {//from www . j ava 2s . com try { handle(socket); } catch (Exception ex) { throw new RuntimeException(ex); } }); } }
From source file:node.Mailbox.java
/** * Accept a message from a socket. Adds the message to the appropriate queue *///from w ww. java2s. c o m private void acceptMessage(Socket socket) { // get the source address String srcIP = socket.getInetAddress().getHostAddress(); ObjectInputStream ois; try { InputStream is = socket.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ois = new ObjectInputStream(bis); // now the Mailbox can block until it receives all message bytes // accept the message object AbstractMessage a = (AbstractMessage) ois.readObject(); println("Received msg " + a.toString()); // TODO MARK MESSAGE WITH OLD TIMESTAMP // save the srcIP for later. srcPort is already part of the message a.srcIP = srcIP; // cast to the appropriate message type if (a.msgType < MessageType.CONTROL) { // call the appropriate verifier, place the message in the queue // and call the appropriate message handler to reconstruct the // message over the network ControlMessage m = (ControlMessage) a; ctrlMsgsRecv.add(m); } else if (a.msgType < MessageType.EVOLVE) { EvolveMessage m = (EvolveMessage) a; evolveMsgsRecv.add(m); } else if (a.msgType < MessageType.DATA) { // TODO handle Data-specific messages (dataset/indexing // information, db webserver address, etc) throw new NoSuchMethodError("Handling DATA messages is not yet implemented"); } } catch (StreamCorruptedException e) { println("Caught StreamCorruptedException: client must have terminated transmission", true); } catch (EOFException e) { println("Caught EOFException: client must have terminated transmission", true); } catch (IOException e) { log.log(Level.SEVERE, "Mailbox error: failed to accept message due to IOException", e); e.printStackTrace(); log.severe(ExceptionUtils.getStackTrace(e)); } catch (ClassNotFoundException e) { log.log(Level.SEVERE, "Mailbox error: failed to accept message due to ClassNotFoundException", e); e.printStackTrace(); log.severe(ExceptionUtils.getStackTrace(e)); } }
From source file:com.myapplication.ServerService.java
@Override protected void onHandleIntent(Intent intent) { ServerSocket serverSocket;/*from w w w .j av a2 s .c om*/ Socket socket; try { serverSocket = new ServerSocket(Constant.SERVER_PORT); while (true) { //Listen for incoming connections on specified port //Block thread until someone connects socket = serverSocket.accept(); clientAddress = socket.getInetAddress().getHostAddress(); InputStream is = socket.getInputStream(); String receivedMessage = CommonUtils.getStringFromInputStream(is); CommonUtils.showToast(receivedMessage); Intent messageIntent = new Intent(Constant.ACTION_MESSAGE_FROM_PEER); messageIntent.putExtra(Constant.KEY_MESSAGE_FROM_PEER, receivedMessage); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(messageIntent); socket.close(); } } catch (Exception e) { CommonUtils.showToast(e.getMessage()); } }
From source file:org.Cherry.Modules.Web.Engine.WebEngineManager.java
HttpServerConnection getHttpServerConnection() throws IOException { final Socket socket = getSocket(); if (null == socket) throw new IllegalStateException(new IllegalArgumentException( new NullPointerException("Undefined 'java.net.Socket' returned by underlying framework!"))); debug("Incoming connection from [{}]", socket.getInetAddress()); return getHttpConnectionFactory().createConnection(socket); }
From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java
/** * Pre-ICS Android had a bug resolving HTTPS addresses. This workaround fixes that bug. * * @param socket The socket to alter/*from w w w . ja v a 2s. c o m*/ * @param host Hostname to connect to * @see <a href="https://code.google.com/p/android/issues/detail?id=13117#c14">https://code.google.com/p/android/issues/detail?id=13117#c14</a> */ private void injectHostname(Socket socket, String host) { try { if (Integer.valueOf(Build.VERSION.SDK) >= 4) { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(socket.getInetAddress(), host); } } catch (Exception ignored) { } }
From source file:org.apache.pulsar.testclient.LoadSimulationClient.java
/** * Start listening for controller commands to create producers and consumers. *///from ww w . j a v a 2s .co m public void run() throws Exception { final ServerSocket serverSocket = new ServerSocket(port); while (true) { // Technically, two controllers can be connected simultaneously, but // non-sequential handling of commands // has not been tested or considered and is not recommended. log.info("Listening for controller command..."); final Socket socket = serverSocket.accept(); log.info("Connected to {}", socket.getInetAddress().getHostName()); executor.submit(() -> { try { handle(socket); } catch (Exception ex) { throw new RuntimeException(ex); } }); } }
From source file:net.lightbody.bmp.proxy.jetty.http.SocketListener.java
/** Create an HttpConnection instance. This method can be used to * override the connection instance.//w ww. jav a2 s.c o m * @param socket The underlying socket. */ protected HttpConnection createConnection(Socket socket) throws IOException { HttpConnection c = new HttpConnection(this, socket.getInetAddress(), socket.getInputStream(), socket.getOutputStream(), socket); return c; }
From source file:nl.nn.adapterframework.ftp.FTPsClient.java
protected Socket _openDataConnection_(int cmdNr, String param) throws IOException { // if explicit FTPS, the socket connection is establisch unsecure if (session.getFtpType() == FtpSession.FTPS_EXPLICIT_SSL || session.getFtpType() == FtpSession.FTPS_EXPLICIT_TLS) { if (session.isProtp()) { // With Prot P the result is returned over a different port // .. send protp commands sendCommand("PBSZ", "0"); checkReply("PBSZ 0"); sendCommand("PROT", "P"); checkReply("PROT P"); sendCommand("PASV"); checkReply("PASV"); // Parse the host and port name to which the result is send String reply = getReplyString(); String line = reply.substring(reply.indexOf('(') + 1, reply.lastIndexOf(')')); String[] hostinfo = line.split(","); String host = hostinfo[0] + "." + hostinfo[1] + "." + hostinfo[2] + "." + hostinfo[3]; int port = (Integer.parseInt(hostinfo[4]) << 8) + Integer.parseInt(hostinfo[5]); log.debug("channel from pasv reply=" + host + ":" + port); InetSocketAddress address = new InetSocketAddress(host, port); // connect to the result address Socket socket = new Socket(); socket.connect(address);// w w w. j a v a2 s. c om socket.setSoTimeout(1000); host = socket.getInetAddress().getHostAddress(); port = socket.getPort(); log.debug("channel from socket=" + host + ":" + port); socket = socketFactory.createSocket(socket, host, port, true); String cmdLine = FTPCommand.getCommand(cmdNr); if (param != null) { cmdLine += ' ' + param; } // send the requested command (over the original socket) <-- toch maar niet! GvB // _sendCommand(cmdLine, _socket_.getOutputStream(), null); sendCommand(cmdNr, param); // return the new socket for the reply return socket; } } return super._openDataConnection_(cmdNr, param); }
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
@Override public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) { try {// w ww. jav a 2 s.c om final X509Certificate selected; final String hostname = socket.getInetAddress().getHostName(); try { final String alias = bookmark.getCredentials().getCertificate(); if (StringUtils.isNotBlank(alias)) { log.info(String.format("Return saved certificate alias %s for host %s", alias, bookmark)); return alias; } selected = callback.choose(keyTypes, issuers, bookmark, MessageFormat.format(LocaleFactory.localizedString( "The server requires a certificate to validate your identity. Select the certificate to authenticate yourself to {0}."), hostname)); } catch (ConnectionCanceledException e) { if (log.isInfoEnabled()) { log.info(String.format("No certificate selected for socket %s", socket)); } return null; } if (null == selected) { if (log.isInfoEnabled()) { log.info(String.format("No certificate selected for socket %s", socket)); } // Disconnect return null; } final String[] aliases = this.getClientAliases(keyTypes, issuers); if (null != aliases) { final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { return null; } for (String alias : aliases) { if (store.getCertificate(alias).equals(selected)) { if (log.isInfoEnabled()) { log.info(String.format("Selected certificate alias %s for certificate %s", alias, selected)); } bookmark.getCredentials().setCertificate(alias); return alias; } } } log.warn(String.format("No matching alias found for selected certificate %s", selected)); // Return null if there are no matches return null; } catch (KeyStoreException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } // Return null if there are no matches return null; }