List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket() throws IOException
From source file:com.nesscomputing.service.discovery.server.TestStaticAnnounce.java
private static final int findUnusedPort() { int port;//from w w w.j a v a 2s. c o m ServerSocket socket = null; try { socket = new ServerSocket(); socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } catch (final IOException ioe) { throw Throwables.propagate(ioe); } finally { try { socket.close(); } catch (final IOException ioe) { // GNDN } } return port; }
From source file:org.apache.axis2.clustering.tribes.WkaBasedMembershipScheme.java
private void configureStaticMembership() throws ClusteringFault { channel.setMembershipService(new WkaMembershipService(primaryMembershipManager)); StaticMember localMember = new StaticMember(); primaryMembershipManager.setLocalMember(localMember); ReceiverBase receiver = (ReceiverBase) channel.getChannelReceiver(); // ------------ START: Configure and add the local member --------------------- Parameter localMemberHost = getParameter(TribesConstants.LOCAL_MEMBER_HOST); Parameter localMemberBindAddress = getParameter(TribesConstants.LOCAL_MEMBER_BIND_ADDRESS); String host = null;//from w ww. j av a 2 s. c o m String bindAddress = null; if (localMemberHost == null && localMemberBindAddress == null) { try { host = Utils.getIpAddress(); bindAddress = host; receiver.setAddress(host); } catch (SocketException e) { String msg = "Could not get local IP address"; log.error(msg, e); throw new ClusteringFault(msg, e); } } else if (localMemberHost != null && localMemberBindAddress == null) { host = ((String) localMemberHost.getValue()).trim(); bindAddress = host; receiver.setAddress(host); } else if (localMemberHost == null && localMemberBindAddress != null) { host = ((String) localMemberBindAddress.getValue()).trim(); bindAddress = host; receiver.setAddress(host); } else if (localMemberHost != null && localMemberBindAddress != null) { host = ((String) localMemberHost.getValue()).trim(); receiver.setAddress(host); bindAddress = ((String) localMemberBindAddress.getValue()).trim(); try { receiver.setBind(InetAddress.getByName(bindAddress)); } catch (UnknownHostException e) { String msg = "Could not get local member bind address"; log.error(msg, e); throw new ClusteringFault(msg, e); } } try { localMember.setHostname(host); } catch (IOException e) { String msg = "Could not set the local member's name"; log.error(msg, e); throw new ClusteringFault(msg, e); } byte[] payload = "ping".getBytes(); localMember.setPayload(payload); Parameter localBindPort = getParameter(TribesConstants.LOCAL_MEMBER_BIND_PORT); // Set the advertised port Parameter localPortParam = getParameter(TribesConstants.LOCAL_MEMBER_PORT); int localPort; if (localBindPort == null) { try { if (localPortParam != null) { localPort = Integer.parseInt(((String) localPortParam.getValue()).trim()); localPort = getLocalPort(new ServerSocket(), bindAddress, localPort, 4000, 100); } else { localPort = getLocalPort(new ServerSocket(), bindAddress, -1, 4000, 100); } } catch (IOException e) { throw new ClusteringFault("Could not allocate local port", e); } } else { localPort = Integer.parseInt(((String) localPortParam.getValue()).trim()); } localMember.setPort(localPort); // Set the bind port if (localBindPort == null) { localBindPort = getParameter(TribesConstants.LOCAL_MEMBER_PORT); } int port; try { if (localBindPort != null) { port = Integer.parseInt(((String) localBindPort.getValue()).trim()); port = getLocalPort(new ServerSocket(), bindAddress, port, 4000, 100); } else { // In cases where the localport needs to be automatically figured out port = getLocalPort(new ServerSocket(), bindAddress, -1, 4000, 100); } } catch (IOException e) { String msg = "Could not allocate the specified port or a port in the range 4000-4100 " + "for local host " + localMember.getHostname() + ". Check whether the IP address specified or inferred for the local " + "member is correct."; log.error(msg, e); throw new ClusteringFault(msg, e); } receiver.setPort(port); localMember.setDomain(localDomain); staticMembershipInterceptor.setLocalMember(localMember); // ------------ END: Configure and add the local member --------------------- // ------------ START: Add other members --------------------- boolean isAtLeastOneWkaMemberReachable = false; Set<Member> unReachableWkaMembers = new HashSet<Member>(); for (Member member : members) { boolean result = addMember(member, payload, localMember, unReachableWkaMembers); // we shouldn't override the isAtLeastOneWkaMemberReachable, if it is true if (!isAtLeastOneWkaMemberReachable) { isAtLeastOneWkaMemberReachable = result; } } if (!isAtLeastOneWkaMemberReachable && !unReachableWkaMembers.isEmpty()) { // if none of the wka members available, we do not let the server to start // we wait for eternity till at least one of the wka members join. do { for (Member member : unReachableWkaMembers) { isAtLeastOneWkaMemberReachable = addMember(member, payload, localMember, unReachableWkaMembers); if (isAtLeastOneWkaMemberReachable) { break; } } try { // retry after 2s Thread.sleep(2000); } catch (InterruptedException ignore) { } } while (!isAtLeastOneWkaMemberReachable); } // mark this object to be GC collected unReachableWkaMembers = null; }
From source file:com.rjfun.cordova.httpd.NanoHTTPD.java
/** * Starts a HTTP server to given port.<p> * Throws an IOException if the socket is already in use *//*from w w w .j a va 2 s . c o m*/ public NanoHTTPD(InetSocketAddress localAddr, AndroidFile wwwroot) throws IOException { myTcpPort = localAddr.getPort(); myRootDir = wwwroot; myServerSocket = new ServerSocket(); myServerSocket.bind(localAddr); myThread = new Thread(new Runnable() { public void run() { try { while (true) new HTTPSession(myServerSocket.accept()); } catch (IOException ioe) { } } }); myThread.setDaemon(true); myThread.start(); }
From source file:fi.iki.elonen.NanoHTTPD.java
/** * Start the server.//from w w w .j a v a2s . c o m * * @throws IOException if the socket is in use. */ public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); if (inputStream == null) { safeClose(finalAccept); unRegisterConnection(finalAccept); } else { asyncRunner.exec(new Runnable() { @Override public void run() { BufferedInputStream bufferedInputStream = null; OutputStream outputStream = null; try { bufferedInputStream = new BufferedInputStream(inputStream); outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, bufferedInputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(bufferedInputStream); safeClose(outputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } } }); } } catch (IOException e) { } } while (!myServerSocket.isClosed()); } }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); }
From source file:us.pserver.revok.HttpConnector.java
/** * Create a bounded <code>ServerSocket</code> * connection with this HttpConnector informations. * @return <code>ServerSocket</code>. * @throws IOException In case of creation error. *///from www . j ava 2 s .c o m public ServerSocket connectServerSocket() throws IOException { ServerSocket sc = new ServerSocket(); sc.bind(this.createSocketAddress()); return sc; }
From source file:org.apache.camel.itest.http.HttpTestServer.java
/** * Starts this test server./*from w ww . jav a 2 s .c om*/ */ public void start() throws Exception { if (servicedSocket != null) { throw new IllegalStateException(this.toString() + " already running"); } ServerSocket ssock; if (sslcontext != null) { SSLServerSocketFactory sf = sslcontext.getServerSocketFactory(); ssock = sf.createServerSocket(); } else { ssock = new ServerSocket(); } ssock.setReuseAddress(true); // probably pointless for port '0' ssock.bind(TEST_SERVER_ADDR); servicedSocket = ssock; listenerThread = new ListenerThread(); listenerThread.setDaemon(false); listenerThread.start(); }
From source file:com.nokia.dempsy.messagetransport.tcp.TcpReceiver.java
protected void bind() throws MessageTransportException { if (serverSocket == null || !serverSocket.isBound()) { try {// ww w. j a v a 2 s .c om InetSocketAddress inetSocketAddress = new InetSocketAddress(destination.inetAddress, destination.port < 0 ? 0 : destination.port); serverSocket = new ServerSocket(); serverSocket.setReuseAddress(true); // this allows the server port to be bound to even if it's in TIME_WAIT serverSocket.bind(inetSocketAddress); destination.port = serverSocket.getLocalPort(); } catch (IOException ioe) { throw new MessageTransportException("Cannot bind to port " + (destination.isEphemeral() ? "(ephemeral port)" : destination.port), ioe); } } }
From source file:org.apache.http.localserver.LocalTestServer.java
/** * Starts this test server./*from ww w .j a va 2 s.co m*/ * Use {@link #getServicePort getServicePort} * to obtain the port number afterwards. */ public void start() throws Exception { if (servicedSocket != null) throw new IllegalStateException(this.toString() + " already running"); ServerSocket ssock; if (sslcontext != null) { SSLServerSocketFactory sf = sslcontext.getServerSocketFactory(); ssock = sf.createServerSocket(); } else { ssock = new ServerSocket(); } ssock.setReuseAddress(true); // probably pointless for port '0' ssock.bind(TEST_SERVER_ADDR); servicedSocket = ssock; listenerThread = new Thread(new RequestListener()); listenerThread.setDaemon(false); listenerThread.start(); }
From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java
@Override protected boolean run() { Log.trace(pathFinderService.dumpConfig()); try {/* ww w . ja va 2 s . c o m*/ try { this.sslServerSocket = makeSSLServerSocket(keyStoreFilePath, ("suckre").toCharArray()); } catch (IOException e1) { Log.warn("NanoHTTP couldn't start SSL because of missing keyfile.", e1); this.sslServerSocket = null; } this.simpleServerSocket = new ServerSocket(); this.simpleServerSocket.setReuseAddress(true); ServerRunnable serverRunnable = new ServerRunnable(socketReadTimeout, simpleServerSocket, this.listeningHost, this.listeningPort, threadService, this, fileService); this.myThread = new Thread(serverRunnable); this.myThread.setDaemon(true); this.myThread.setName("NanoHttpService Main Listener"); this.myThread.start(); while (!serverRunnable.isBinded() && serverRunnable.getBindException() == null) { try { Thread.sleep(10L); } catch (Throwable t) { // on android this may not be allowed, that's why we // catch throwable the wait should be very short because we // are // just waiting for the bind of the socket } } if (serverRunnable.getBindException() != null) { throw serverRunnable.getBindException(); } } catch (IOException e) { Log.fatal("NanoHttpService failed to start:", e); return false; } return true; }
From source file:helma.main.Server.java
/** * Check whether a server port is available by trying to open a server socket *///from ww w . j a va 2 s . c o m private static void checkPort(InetSocketAddress endpoint) throws IOException { try { ServerSocket sock = new ServerSocket(); sock.bind(endpoint); sock.close(); } catch (IOException x) { throw new IOException("Error binding to " + endpoint + ": " + x.getMessage()); } }