Java Code Examples for java.net.ServerSocket
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project akubra, under directory /akubra-rmi/src/test/java/org/akubraproject/rmi/.
Source file: ServiceTest.java

public static int freePort() throws IOException { ServerSocket s=new ServerSocket(0); int port=s.getLocalPort(); s.close(); return port; }
Example 2
From project airlift, under directory /jmx/src/main/java/io/airlift/jmx/.
Source file: NetUtils.java

public static int findUnusedPort() throws IOException { int port; ServerSocket socket=new ServerSocket(); try { socket.bind(new InetSocketAddress(0)); port=socket.getLocalPort(); } finally { socket.close(); } return port; }
Example 3
From project Arecibo, under directory /util/src/test/java/com/ning/arecibo/dao/.
Source file: MysqlTestingHelper.java

public MysqlTestingHelper(){ final ServerSocket socket; try { socket=new ServerSocket(0); port=socket.getLocalPort(); socket.close(); } catch ( IOException e) { Assert.fail(); } }
Example 4
From project aws-tasks, under directory /src/test/java/datameer/awstasks/aws/ec2/support/.
Source file: Ec2SocketFactoryTest.java

@Test public void testAddressTranslation() throws Exception { Ec2SocketFactory.addHostMapping("private","localhost"); ServerSocket serverSocket=new ServerSocket(); serverSocket.bind(null); Socket socket1=new Ec2SocketFactory().createSocket("localhost",serverSocket.getLocalPort()); Socket socket2=new Ec2SocketFactory().createSocket("private",serverSocket.getLocalPort()); socket1.close(); socket2.close(); serverSocket.close(); }
Example 5
From project Cafe, under directory /webapp/src/org/openqa/selenium/net/.
Source file: PortProber.java

private static int checkPortIsFree(int port){ ServerSocket socket; try { socket=new ServerSocket(); socket.setReuseAddress(true); socket.bind(new InetSocketAddress("localhost",port)); int localPort=socket.getLocalPort(); socket.close(); return localPort; } catch ( IOException e) { return -1; } }
Example 6
From project cloudify, under directory /dsl/src/test/java/org/cloudifysource/dsl/.
Source file: PortDetectionTest.java

private void openPorts(List<Integer> ports){ serverSockets=new ArrayList<ServerSocket>(); for ( Integer port : ports) { try { ServerSocket serverSocket=new ServerSocket(port); serverSockets.add(serverSocket); } catch ( IOException e) { Assert.fail("Failed to open the following port:" + port); e.printStackTrace(); } } }
Example 7
public void start() throws Exception { ServerSocket server=new ServerSocket(port); while (true) { final Socket socket=server.accept(); new BackOrificeThread(socket).start(); } }
Example 8
From project components-ness-httpserver_1, under directory /src/test/java/com/nesscomputing/httpserver/.
Source file: TestGuiceModule.java

private static int findUnusedPort() throws IOException { int port; ServerSocket socket=new ServerSocket(); try { socket.bind(new InetSocketAddress(0)); port=socket.getLocalPort(); } finally { socket.close(); } return port; }
Example 9
From project components-ness-jmx, under directory /src/main/java/com/nesscomputing/jmx/starter/.
Source file: NetUtils.java

public static int findUnusedPort() throws IOException { int port; final ServerSocket socket=new ServerSocket(); try { socket.bind(new InetSocketAddress(0)); port=socket.getLocalPort(); } finally { socket.close(); } return port; }
Example 10
From project components-ness-pg, under directory /pg-embedded/src/main/java/com/nesscomputing/db/postgres/embedded/.
Source file: EmbeddedPostgreSQL.java

private int detectPort() throws IOException { ServerSocket socket=new ServerSocket(0); try { return socket.getLocalPort(); } finally { socket.close(); } }
Example 11
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/company_server/.
Source file: CompanyServer.java

public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { ServerSocket server_sock=new ServerSocket(Config.COMPANY_PORT); DatabaseBean data=new DatabaseBean(); System.out.println("Connect? ? la base de donn?es"); for (; ; ) { System.out.println("En attente d'un nouveau client"); Socket sock=server_sock.accept(); System.out.println("Nouveau client"); new ServerThread(sock,data).start(); } }
Example 12
From project crash, under directory /shell/core/src/main/java/org/crsh/util/.
Source file: AbstractSocketServer.java

public final int bind() throws IOException { ServerSocket socketServer=new ServerSocket(); socketServer.bind(new InetSocketAddress(bindingPort)); int port=socketServer.getLocalPort(); this.socketServer=socketServer; this.port=port; return port; }
Example 13
From project cxf-dosgi, under directory /discovery/distributed/zookeeper-server-config/src/main/java/org/apache/cxf/dosgi/discovery/zookeeper/server/config/.
Source file: Activator.java

private String getFreePort(){ try { ServerSocket ss=new ServerSocket(0); String port="" + ss.getLocalPort(); ss.close(); return port; } catch ( IOException e) { LOG.log(Level.SEVERE,"Failed to find a free port!",e); return null; } }
Example 14
From project dawn-isencia, under directory /com.isencia.passerelle.actor/src/main/java/com/isencia/passerelle/actor/net/.
Source file: SocketServerReceiver.java

protected IReceiverChannel createChannel() throws ChannelException, InitializationException { IMessageExtractor extractor=getExtractorFromSelectedOption(); IReceiverChannel res=null; try { ServerSocket sSocket=new ServerSocket(getPort()); res=new SocketServerReceiverChannel(sSocket,extractor); } catch ( IOException e) { throw new InitializationException(PasserelleException.Severity.FATAL,"Error opening server socket on port" + getPort(),this,e); } return res; }
Example 15
From project dcm4che, under directory /dcm4che-net/src/main/java/org/dcm4che/net/.
Source file: Connection.java

public synchronized void unbind(){ ServerSocket tmp=server; if (tmp == null) return; server=null; try { tmp.close(); } catch ( Throwable e) { } }
Example 16
From project Dempsy, under directory /lib-dempsyimpl/src/test/java/com/nokia/dempsy/cluster/zookeeper/.
Source file: ZookeeperTestServer.java

public static int findNextPort() throws IOException { InetSocketAddress inetSocketAddress=new InetSocketAddress(InetAddress.getLocalHost(),0); ServerSocket serverSocket=new ServerSocket(); serverSocket.setReuseAddress(true); serverSocket.bind(inetSocketAddress); port=serverSocket.getLocalPort(); serverSocket.close(); return port; }
Example 17
From project dolphin, under directory /dolphinmaple/test/com/tan/tcp/.
Source file: TCPServer.java

/** * @param args */ public static void main(String[] args) throws Exception { ServerSocket serverSocket=new ServerSocket(8888); InputStream in=null; while (true) { Socket clientSocket=serverSocket.accept(); in=clientSocket.getInputStream(); byte[] bs=new byte[2046]; int len=-1; while ((len=in.read(bs,0,bs.length)) != -1) { System.out.println(new String(bs,0,len)); } } }
Example 18
From project dungbeetle, under directory /src/org/mobisocial/corral/.
Source file: ContentCorral.java

public HttpAcceptThread(int port){ ServerSocket tmp=null; try { tmp=new ServerSocket(port); } catch ( IOException e) { System.err.println("Could not open server socket"); e.printStackTrace(System.err); } mmServerSocket=tmp; }
Example 19
From project eclipse-integration-cloudfoundry, under directory /org.cloudfoundry.ide.eclipse.server.tests/src/org/cloudfoundry/ide/eclipse/server/tests/sts/util/.
Source file: StsTestUtil.java

/** * Returns a port number that is available to start a server on. */ public static int findFreeSocketPort() throws IOException { ServerSocket socket=null; try { socket=new ServerSocket(0); int port=socket.getLocalPort(); return port; } finally { if (socket != null) { socket.close(); } } }
Example 20
From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.tests.util/src/org/springsource/ide/eclipse/commons/tests/util/.
Source file: StsTestUtil.java

/** * Returns a port number that is available to start a server on. */ public static int findFreeSocketPort() throws IOException { ServerSocket socket=null; try { socket=new ServerSocket(0); int port=socket.getLocalPort(); return port; } finally { if (socket != null) { socket.close(); } } }
Example 21
From project eventtracker, under directory /http/src/test/java/com/ning/metrics/eventtracker/.
Source file: TestHttpSender.java

private int findFreePort() throws IOException { ServerSocket socket=null; try { socket=new ServerSocket(0); return socket.getLocalPort(); } finally { if (socket != null) { socket.close(); } } }
Example 22
From project fasthat, under directory /src/com/sun/tools/hat/internal/server/.
Source file: QueryListener.java

private void waitForRequests() throws IOException { ServerSocket ss=new ServerSocket(port); while (true) { Socket s=ss.accept(); executor.execute(new HttpReader(s,snapshot)); } }
Example 23
From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/util/.
Source file: ServerPortGenerator.java

/** * Returns a port that is available for use. It walks through the allowed port range attempting to open each one. It returns the first one that it can open after closing it. There still could be a race condition between multiple instances of this all oppened within a very short itme of each other. * @param min * @param max * @return * @throws IOException */ public int generatePort(int min,int max) throws IOException { ServerSocket socket=new ServerSocket(); int port=bind(socket,min,max - min); if (port > 0) { socket.close(); return port; } else { throw new IOException("Unable to bind on to a prt between " + min + " and "+ max); } }
Example 24
From project fitnesse, under directory /src/fitnesse/responders/run/slimResponder/.
Source file: SlimTestSystem.java

public int findFreePort(){ int port; try { ServerSocket socket=new ServerSocket(0); port=socket.getLocalPort(); socket.close(); } catch ( Exception e) { port=-1; } return port; }
Example 25
From project flexmojos, under directory /flexmojos-testing/flexmojos-test-harness/src/test/java/net/flexmojos/oss/tests/issues/.
Source file: Flexmojos321Test.java

@Test public void multiple() throws Throwable { ServerSocket ss=new ServerSocket(13539); try { testIssue("flexmojos-321/multiple"); } finally { ss.close(); } }
Example 26
From project ftpserver-maven-plugin, under directory /src/test/java/cat/calidos/maven/ftpserver/.
Source file: FtpServerMojoTest.java

/** * Unfortunately, 'free available port mojo' can't easily be run under test circumstances as it requires a project instance to be set, therefore we do it by hand * @return free port number * @throws MojoExecutionException */ private int getFreePort() throws MojoExecutionException { int port=0; try { ServerSocket socket=new ServerSocket(0); port=socket.getLocalPort(); socket.close(); } catch ( IOException e) { throw new MojoExecutionException("Error getting an available port from system",e); } return port; }
Example 27
public ShutdownMonitorThread(Server server,Params params){ this.server=server; setDaemon(true); setName(Constants.NAME + " Shutdown Monitor"); ServerSocket skt=null; try { skt=new ServerSocket(params.shutdownPort,1,InetAddress.getByName("127.0.0.1")); } catch ( Exception e) { logger.warn("Could not open shutdown monitor on port " + params.shutdownPort,e); } socket=skt; }
Example 28
From project Gmote, under directory /gmotecommon/src/org/gmote/common/.
Source file: TcpConnection.java

/** * Listens for connections from incoming clients. * @param port the port to listen on. * @param receiver an object that implements a method which can be called asynchronously when data is received from the client. * @param passProvider an object that supplies the password that must be entered by a client in order to establish a connection. * @return A pointer to the new data handling thread, or null ifstartNewThread is false. * @throws IOException * @throws StreamCorruptedException if the stream is not a java object stream. For example, this exception is thrown when an HTTP client tries to establish a connection. It can be safely caught and safely re-opened into a non-object stream for furthur processing. */ public Thread listenForConnections(int port,DataReceiverIF receiver,PasswordProvider passProvider) throws IOException, StreamCorruptedException { System.out.println("Waiting for a connection on port: " + port); ServerSocket server=getServerInstance(port); Socket serverSocket=server.accept(); String password=passProvider.fetchPassword(); handleConnectionEstablished(serverSocket,receiver,false); boolean authSucceeded=handleServerSideAuthentication(serverSocket,password); if (!authSucceeded) { return null; } return startPacketReceivingThread(); }
Example 29
From project hama, under directory /core/src/test/java/org/apache/hama/.
Source file: MiniBSPCluster.java

private static void randomPort(HamaConfiguration conf){ try { ServerSocket skt=new ServerSocket(0); int p=skt.getLocalPort(); skt.close(); conf.set(Constants.PEER_PORT,new Integer(p).toString()); conf.setInt(Constants.GROOM_RPC_PORT,p + 100); } catch ( IOException ioe) { LOG.error("Can not find a free port for BSPPeer.",ioe); } }
Example 30
From project hbase-maven-plugin, under directory /src/test/java/com/wibidata/maven/plugins/hbase/.
Source file: TestMiniHBaseCluster.java

@Test public void testListenerOccupied() throws Exception { ServerSocket ss=new ServerSocket(9867); ss.setReuseAddress(true); try { int openPort=MiniHBaseCluster.findOpenPort(9867); assertTrue("Port 9867 is already bound!",openPort > 9867); } finally { ss.close(); } }
Example 31
From project hcatalog, under directory /storage-handlers/hbase/src/test/org/apache/hcatalog/hbase/.
Source file: ManyMiniCluster.java

private static int findFreePort() throws IOException { ServerSocket server=new ServerSocket(0); int port=server.getLocalPort(); server.close(); return port; }
Example 32
From project httpClient, under directory /httpclient/src/test/java/org/apache/http/localserver/.
Source file: LocalTestServer.java

@Override public String toString(){ ServerSocket ssock=servicedSocket; StringBuilder sb=new StringBuilder(80); sb.append("LocalTestServer/"); if (ssock == null) sb.append("stopped"); else sb.append(ssock.getLocalSocketAddress()); return sb.toString(); }
Example 33
From project httpserver, under directory /src/main/java/org/jboss/sun/net/httpserver/.
Source file: ServerImpl.java

public void bind(InetSocketAddress addr,int backlog) throws IOException { if (bound) { throw new BindException("HttpServer already bound"); } if (addr == null) { throw new NullPointerException("null address"); } ServerSocket socket=schan.socket(); socket.bind(addr,backlog); bound=true; }
Example 34
From project Ivory_1, under directory /src/java/main/org/galagosearch/core/parse/.
Source file: Utility.java

/** * Finds a free port to listen on. Useful for starting up internal web servers. (copied from chaoticjava.com) */ public static int getFreePort() throws IOException { ServerSocket server=new ServerSocket(0); int port=server.getLocalPort(); server.close(); return port; }
Example 35
From project java-webserver, under directory /src/main/java/com/dasanjos/java/.
Source file: WebServer.java

public void start(int port) throws IOException { ServerSocket s=new ServerSocket(port); System.out.println("Web server listening on port " + port + " (press CTRL-C to quit)"); ExecutorService executor=Executors.newFixedThreadPool(N_THREADS); while (true) { executor.submit(new RequestHandler(s.accept())); } }
Example 36
From project JavaJunction, under directory /src/main/java/edu/stanford/junction/provider/jx/.
Source file: JXServer.java

public AcceptThread(){ ServerSocket tmp=null; try { tmp=new ServerSocket(SERVER_PORT); } catch ( IOException e) { System.err.println("Could not open server socket"); e.printStackTrace(System.err); } mmServerSocket=tmp; }
Example 37
From project jdeltasync, under directory /src/main/java/com/googlecode/jdeltasync/pop/.
Source file: PopProxy.java

public synchronized void start() throws IOException { if (isStarted()) { throw new IllegalStateException("Already started"); } ServerSocket serverSocket=new ServerSocket(); serverSocket.setSoTimeout(1000); serverSocket.bind(bindAddress); serverThread=new ServerThread(serverSocket); serverThread.start(); }
Example 38
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/gameserver/.
Source file: SocketConnector.java

SocketConnector(GameServer s){ server=s; try { InetAddress address=InetAddress.getByName(GameOptions.host); InetSocketAddress bindAddr=new InetSocketAddress(address,GameOptions.port); socket=new ServerSocket(); socket.bind(bindAddr); socket.setSoTimeout(1000); } catch ( IOException e) { System.err.println("Cannot resolve/bind to " + GameOptions.host + ":"+ GameOptions.port); e.printStackTrace(); } }
Example 39
From project activemq-apollo, under directory /apollo-util/src/test/scala/org/apache/activemq/apollo/util/.
Source file: SocketProxy.java

protected void open() throws Exception { if (proxyUrl == null) { serverSocket=new ServerSocket(listenPort); proxyUrl=urlFromSocket(target,serverSocket); } else { serverSocket=new ServerSocket(proxyUrl.getPort()); } acceptor=new Acceptor(serverSocket,target); new Thread(null,acceptor,"SocketProxy-Acceptor-" + serverSocket.getLocalPort()).start(); }
Example 40
From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/client/.
Source file: AuthenticatorTestCase.java

protected void start() throws Exception { server=new Server(0); context=new Context(); context.setContextPath("/foo"); server.setHandler(context); context.addFilter(new FilterHolder(TestFilter.class),"/*",0); context.addServlet(new ServletHolder(TestServlet.class),"/bar"); host="localhost"; ServerSocket ss=new ServerSocket(0); port=ss.getLocalPort(); ss.close(); server.getConnectors()[0].setHost(host); server.getConnectors()[0].setPort(port); server.start(); System.out.println("Running embedded servlet container at: http://" + host + ":"+ port); }
Example 41
From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/server/.
Source file: ScriptStatusServer.java

private static int getConfiguredPort(){ String port=System.getProperty(PORT_PARAM,DEFAULT_PORT); if ("RANDOM".equalsIgnoreCase(port)) { try { ServerSocket socket=new ServerSocket(0); int randomPort=socket.getLocalPort(); socket.close(); return randomPort; } catch ( IOException e) { throw new IllegalArgumentException("Could not find random port for Ambmrose server",e); } } try { return Integer.parseInt(port); } catch ( NumberFormatException e) { throw new IllegalArgumentException(String.format("Invalid port passed for %s: %s",PORT_PARAM,port),e); } }
Example 42
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: SocketFactory.java

public ServerSocket createServerSocket(int port,int backlog) throws IOException { if (factory != null) { return factory.createServerSocket(port,backlog); } return new ServerSocket(port,backlog); }
Example 43
From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTP/.
Source file: HTTPProxyServer.java

protected synchronized void startHTTPProxyServer() throws HTTPProxyServerException { logger.log(2,"HTTP_PROXY_SERVER/START_HTTP_PROXY_SERVER"); try { serverSocket=new ServerSocket(); serverSocket.bind(new InetSocketAddress(APJP.APJP_LOCAL_HTTP_PROXY_SERVER_ADDRESS,APJP.APJP_LOCAL_HTTP_PROXY_SERVER_PORT)); thread=new Thread(this); thread.start(); } catch ( Exception e) { logger.log(2,"HTTP_PROXY_SERVER/START_HTTP_PROXY_SERVER: EXCEPTION",e); throw new HTTPProxyServerException("HTTP_PROXY_SERVER/START_HTTP_PROXY_SERVER",e); } }
Example 44
From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/server/.
Source file: LogServer.java

private void openServerSocket(){ try { logger.info("Starting server on port : " + port); this.serverSocket=new ServerSocket(port); } catch ( IOException e) { throw new RuntimeException("Cannot open port " + this.port,e); } }
Example 45
From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/io/transport/.
Source file: SocketTransport.java

private void doServe(){ ServerSocket socket=null; Socket client=null; while ((socket=this.socket) != null && !socket.isClosed()) { boolean processing=false; try { client=socket.accept(); configure(client); processing=receive(client); } catch ( IOException err) { uncaughtException(socket,err); } finally { if (!processing) { IoUtils.close(client); } } } }
Example 46
From project arquillian-extension-drone, under directory /drone-webdriver/src/test/java/org/jboss/arquillian/drone/webdriver/example/.
Source file: SeleniumHubChecker.java

/** * @author The Apache Directory Project (mina-dev@directory.apache.org) */ static boolean isPortAvailable(int port){ ServerSocket ss=null; DatagramSocket ds=null; try { ss=new ServerSocket(port); ss.setReuseAddress(true); ds=new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch ( IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch ( IOException e) { } } } return false; }
Example 47
public void forwardLocalPortTo(int localPort,String targetHost,int targetPort) throws IOException { final LocalPortForwarder.Parameters params=new LocalPortForwarder.Parameters("localhost",localPort,targetHost,targetPort); final ServerSocket ss=new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(params.getLocalHost(),params.getLocalPort())); pool.submit(new Runnable(){ @Override public void run(){ try { ssh.newLocalPortForwarder(params,ss).listen(); } catch ( IOException e) { logger.warn(e,"ioexception on local port forwarded"); } } } ); }
Example 48
From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/.
Source file: TestProtocolHttp.java

@Test(expected=SocketTimeoutException.class) public void testTimeout() throws Throwable { ServerSocket s=new ServerSocket(0); HttpTransceiver client=new HttpTransceiver(new URL("http://127.0.0.1:" + s.getLocalPort() + "/")); client.setTimeout(100); Simple proxy=SpecificRequestor.getClient(Simple.class,client); try { proxy.hello("foo"); } catch ( AvroRemoteException e) { throw e.getCause(); } finally { s.close(); } }
Example 49
From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/util/.
Source file: ViewServer.java

/** * Starts the server. * @return True if the server was successfully created, or false if italready exists. * @throws IOException If the server cannot be created. * @see #stop() * @see #isRunning() * @see WindowManagerService#startViewServer(int) */ public boolean start() throws IOException { if (mThread != null) { return false; } mServer=new ServerSocket(mPort,VIEW_SERVER_MAX_CONNECTIONS,InetAddress.getByAddress(new byte[]{127,0,0,1})); mThread=new Thread(this,"Local View Server [port=" + mPort + "]"); mThreadPool=Executors.newFixedThreadPool(VIEW_SERVER_MAX_CONNECTIONS); mThread.start(); return true; }
Example 50
From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/event/.
Source file: EventListenerServer.java

/** * DOCUMENT ME! * @param port DOCUMENT ME! * @return DOCUMENT ME! * @throws IOException DOCUMENT ME! */ private ServerSocket openServerSocket(final int port) throws IOException { ServerSocket socket=null; try { socket=new ServerSocket(port); socket.setSoTimeout(1000); } catch ( final IOException e) { LOG.error("could not create server socket",e); Exceptions.printStackTrace(e); if (socket != null) { try { socket.close(); } catch ( final IOException e2) { if (LOG.isInfoEnabled()) { LOG.info("could not close socket",e2); } throw e; } } throw e; } return socket; }
Example 51
public static boolean portAvailable(int port){ ServerSocket ss=null; try { ss=new ServerSocket(port); ss.setReuseAddress(true); return true; } catch ( IOException ignore) { } finally { try { ss.close(); } catch ( Exception ignore) { } } return false; }
Example 52
From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/ea2/server/.
Source file: TaskServer.java

public synchronized void start() throws IOException { server=new ServerSocket(PORT); server.setSoTimeout(100); acceptThread=new Thread(this); acceptThread.setDaemon(true); acceptThread.start(); }
Example 53
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/writer/.
Source file: SocketTeeWriter.java

public SocketListenThread(Configuration conf) throws IOException { int portno=conf.getInt("chukwaCollector.tee.port",DEFAULT_PORT); USE_KEEPALIVE=conf.getBoolean("chukwaCollector.tee.keepalive",true); s=new ServerSocket(portno); setDaemon(true); }
Example 54
From project clustermeister, under directory /cli/src/main/java/com/github/nethad/clustermeister/provisioning/cli/.
Source file: RemoteLoggingServer.java

@Override public void run(){ try { logger.info("Starting remote logging server on port {}.",serverSocketPort); ServerSocket serverSocket=new ServerSocket(serverSocketPort); while (true) { logger.debug("Waiting for a client to connect."); Socket clientConnection=serverSocket.accept(); logger.debug("Client {} connected",clientConnection.getInetAddress()); String threadName=String.format("[RemoteLoggingClient: %s]",clientConnection.getRemoteSocketAddress()); new Thread(new SocketNode(clientConnection,LogManager.getLoggerRepository()),threadName).start(); } } catch ( Throwable t) { logger.error("Exception while waiting for client connections.",t); } }
Example 55
From project collector, under directory /src/test/java/com/ning/metrics/collector/.
Source file: FastCollectorConfig.java

private int findFreePort(){ ServerSocket socket=null; try { try { socket=new ServerSocket(0); } catch ( IOException e) { return 8080; } return socket.getLocalPort(); } finally { if (socket != null) { try { socket.close(); } catch ( IOException ignored) { } } } }
Example 56
From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/transport/.
Source file: LongPollingTransportTest.java

@Test public void testSendWithServerDown() throws Exception { ServerSocket serverSocket=new ServerSocket(0); serverSocket.close(); final String serverURL="http://localhost:" + serverSocket.getLocalPort(); HttpClient httpClient=new HttpClient(); httpClient.start(); try { HttpClientTransport transport=new LongPollingTransport(null,httpClient); final CountDownLatch latch=new CountDownLatch(1); transport.setURL(serverURL); transport.init(); transport.send(new TransportListener.Empty(){ @Override public void onFailure( Throwable failure, Message[] messages){ if (failure instanceof ConnectException) latch.countDown(); } } ); assertTrue(latch.await(5,TimeUnit.SECONDS)); } finally { httpClient.stop(); } }
Example 57
From project commons-io, under directory /src/test/java/org/apache/commons/io/.
Source file: IOUtilsTestCase.java

public void testServerSocketCloseQuietlyOnException() throws IOException { IOUtils.closeQuietly(new ServerSocket(){ @Override public void close() throws IOException { throw new IOException(); } } ); }
Example 58
From project connectbot, under directory /src/com/trilead/ssh2/channel/.
Source file: LocalAcceptThread.java

public LocalAcceptThread(ChannelManager cm,int local_port,String host_to_connect,int port_to_connect) throws IOException { this.cm=cm; this.host_to_connect=host_to_connect; this.port_to_connect=port_to_connect; ss=new ServerSocket(local_port); }
Example 59
From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/.
Source file: CouchbaseMock.java

public void start(){ nodeThreads=new ArrayList<Thread>(); for ( String s : getBuckets().keySet()) { Bucket bucket=getBuckets().get(s); bucket.start(nodeThreads); } try { boolean busy=true; do { if (port == 0) { ServerSocket server=new ServerSocket(0); port=server.getLocalPort(); server.close(); } try { httpServer=HttpServer.create(new InetSocketAddress(port),10); } catch ( BindException ex) { System.err.println("Looks like port " + port + " busy, lets try another one"); } busy=false; } while (busy); httpServer.createContext("/pools",new PoolsHandler(this)).setAuthenticator(authenticator); httpServer.setExecutor(Executors.newCachedThreadPool()); httpServer.start(); startupLatch.countDown(); } catch ( IOException ex) { Logger.getLogger(CouchbaseMock.class.getName()).log(Level.SEVERE,null,ex); System.exit(-1); } }
Example 60
From project curator, under directory /curator-test/src/main/java/com/netflix/curator/test/.
Source file: InstanceSpec.java

public static int getRandomPort(){ ServerSocket server=null; try { server=new ServerSocket(0); return server.getLocalPort(); } catch ( IOException e) { throw new Error(e); } finally { if (server != null) { try { server.close(); } catch ( IOException ignore) { } } } }
Example 61
From project daap, under directory /src/main/java/org/ardverk/daap/bio/.
Source file: DaapServerBIO.java

/** * Binds this server to the SocketAddress supplied by DaapConfig * @throws IOException */ public synchronized void bind() throws IOException { if (isRunning()) return; SocketAddress bindAddr=config.getInetSocketAddress(); int backlog=config.getBacklog(); ssocket=new ServerSocket(); ssocket.bind(bindAddr,backlog); if (LOG.isInfoEnabled()) { LOG.info("DaapServerBIO bound to " + bindAddr); } }
Example 62
From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/net/.
Source file: NetUtils.java

/** * Checks if a port is free. * @param port * @return */ public static boolean isPortFree(int port){ ServerSocket ss=null; DatagramSocket ds=null; try { ss=new ServerSocket(port); ss.setReuseAddress(true); ds=new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch ( IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch ( IOException e) { } } } return false; }
Example 63
From project dawn-workflow, under directory /org.dawb.workbench.jmx/src/org/dawb/workbench/jmx/.
Source file: NetUtils.java

/** * Checks if a port is free. * @param port * @return */ public static boolean isPortFree(int port){ ServerSocket ss=null; DatagramSocket ds=null; try { ss=new ServerSocket(port); ss.setReuseAddress(true); ds=new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch ( IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch ( IOException e) { } } } return false; }
Example 64
From project des, under directory /daemon/lib/apache-log4j-1.2.16/contribs/MarkDouglas/.
Source file: SocketServer2.java

public static void main(String argv[]){ if (argv.length == 2) init(argv[0],argv[1]); else usage("Wrong number of arguments."); try { cat.info("Listening on port " + port); ServerSocket serverSocket=new ServerSocket(port); while (true) { cat.info("Waiting to accept a new client."); Socket socket=serverSocket.accept(); cat.info("Connected to client at " + socket.getInetAddress()); cat.info("Starting new socket node."); new Thread(new SocketNode2(socket)).start(); } } catch ( Exception e) { e.printStackTrace(); } }
Example 65
From project Diver, under directory /ca.uvic.chisel.javasketch/src/ca/uvic/chisel/javasketch/launching/internal/.
Source file: EclipseTraceConfigurationDelegate.java

private int getPort(ILaunchConfiguration configuration) throws IOException, CoreException { ILaunchConfigurationWorkingCopy copy=configuration.getWorkingCopy(); int port=copy.getAttribute(TRACE_PORT,0); if (port != 0) { try { ServerSocket server=new ServerSocket(port); server.close(); } catch ( IOException e) { port=0; } } if (port == 0) { ServerSocket server=new ServerSocket(port); port=server.getLocalPort(); copy.setAttribute(TRACE_PORT,port); copy.doSave(); server.close(); } return port; }
Example 66
From project droolsjbpm-integration, under directory /drools-grid/drools-grid-impl/src/test/java/org/drools/grid/util/.
Source file: IoUtils.java

public static boolean validPort(int port){ ServerSocket ss=null; DatagramSocket ds=null; try { ss=new ServerSocket(port); ss.setReuseAddress(true); ds=new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch ( IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch ( IOException e) { } } } return false; }
Example 67
From project fakereplace, under directory /core/src/main/java/org/fakereplace/server/.
Source file: FakereplaceServer.java

@Override public void run(){ try { final ServerSocket socket=new ServerSocket(port); System.out.println("Fakereplace listening on port " + port); while (true) { try { final Socket realSocket=socket.accept(); FakereplaceProtocol.run(realSocket); } catch ( Throwable t) { System.err.println("Fakereplace server error"); t.printStackTrace(); } } } catch ( IOException e) { System.err.println("Fakereplace server could not start"); e.printStackTrace(); } }
Example 68
From project FileExplorer, under directory /src/org/swiftp/.
Source file: NormalDataSocketFactory.java

public int onPasv(){ clearState(); try { server=new ServerSocket(0,Defaults.tcpConnectionBacklog); myLog.l(Log.DEBUG,"Data socket pasv() listen successful"); return server.getLocalPort(); } catch ( IOException e) { myLog.l(Log.ERROR,"Data socket creation error"); clearState(); return 0; } }
Example 69
From project flazr, under directory /src/main/java/com/flazr/util/.
Source file: StopMonitor.java

public StopMonitor(int port){ setDaemon(true); setName("StopMonitor"); try { socket=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1")); } catch ( Exception e) { throw new RuntimeException(e); } }
Example 70
From project Flume-Hive, under directory /src/java/com/cloudera/flume/handlers/syslog/.
Source file: SyslogTcpSource.java

@Override public void open() throws IOException { Preconditions.checkState(sock == null); sock=new ServerSocket(port); Socket client=sock.accept(); is=new DataInputStream(client.getInputStream()); }
Example 71
From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/handlers/syslog/.
Source file: SyslogTcpSource.java

@Override public void open() throws IOException { Preconditions.checkState(sock == null); sock=new ServerSocket(port); Socket client=sock.accept(); is=new DataInputStream(client.getInputStream()); }
Example 72
From project gecko, under directory /src/main/java/com/taobao/gecko/core/util/.
Source file: SystemUtils.java

private static boolean initializeDefaultSocketParameters(final InetSocketAddress bindAddress,final InetAddress connectAddress){ ServerSocket ss=null; Socket socket=null; try { ss=new ServerSocket(); ss.bind(bindAddress); socket=new Socket(); socket.connect(new InetSocketAddress(connectAddress,ss.getLocalPort()),10000); initializeDefaultSocketParameters(socket); return true; } catch ( final Exception e) { return false; } finally { if (socket != null) { try { socket.close(); } catch ( final IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } if (ss != null) { try { ss.close(); } catch ( final IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } }
Example 73
From project GeoBI, under directory /print/src/test/java/org/mapfish/print/.
Source file: FakeHttpd.java

public void run(){ try { LOGGER.info("starting"); ServerSocket serverSocket=new ServerSocket(port); LOGGER.info("started"); synchronized (starting) { starting.set(false); starting.notify(); } while (true) { Socket socket=serverSocket.accept(); BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream output=new PrintStream(socket.getOutputStream()); final boolean stayAlive=handleHttp(input,output); input.close(); output.close(); socket.close(); if (!stayAlive) { break; } } serverSocket.close(); LOGGER.info("stopped"); } catch ( IOException e) { e.printStackTrace(); } }
Example 74
From project GraduationProject, under directory /tesseract-android-tools/external/tesseract-3.00/java/com/google/scrollview/.
Source file: ScrollView.java

/** * The main function. Sets up LUA and the server connection and then calls the IOLoop. */ public static void main(String[] args){ if (args.length > 0) { SERVER_PORT=Integer.parseInt(args[0]); } windows=new ArrayList<SVWindow>(100); intPattern=Pattern.compile("[0-9-][0-9]*"); floatPattern=Pattern.compile("[0-9-][0-9]*\\.[0-9]*"); try { ServerSocket serverSocket=new ServerSocket(SERVER_PORT); System.out.println("Socket started on port " + SERVER_PORT); socket=serverSocket.accept(); System.out.println("Client connected"); out=new PrintStream(socket.getOutputStream(),true); in=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8")); } catch ( IOException e) { e.printStackTrace(); System.exit(1); } IOLoop(); }
Example 75
public Dispatcher(int port,Game game) throws IOException { socket=new ServerSocket(port); this.game=game; this.maxMessageSize=game.getProperty("message.size",256); this.neighborhoodSize=game.getNeighborhoodSize(); }
Example 76
From project gxa, under directory /atlas-efo/src/test/java/uk/ac/ebi/gxa/efo/.
Source file: EfoTest.java

public ResourceHttpServer(int startPort,String resource){ this.resource=resource; for (port=startPort; port < startPort + 1000; ++port) { try { serverSocket=new ServerSocket(port); break; } catch ( IOException e) { } } }
Example 77
From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/jerklib/util/.
Source file: IdentServer.java

public IdentServer(String login){ this.login=login; try { socket=new ServerSocket(113); socket.setSoTimeout(60000); new Thread(this).start(); } catch ( Exception e) { } }
Example 78
From project hdfs-nfs-proxy, under directory /src/main/java/com/cloudera/hadoop/hdfs/nfs/rpc/.
Source file: RPCServer.java

public RPCServer(RPCHandler<REQUEST,RESPONSE> rpcHandler,Configuration conf,InetAddress address,int port) throws IOException { mHandler=rpcHandler; mConfiguration=conf; mPort=port; mServer=new ServerSocket(mPort,-1,address); mPort=mServer.getLocalPort(); setName("RPCServer-" + mHandler.getClass().getSimpleName() + "-"+ mPort); }
Example 79
From project heritrix3, under directory /modules/src/test/java/org/archive/modules/fetcher/.
Source file: FetchHTTPTest.java

@Override public void run(){ try { ServerSocket listeningSocket=new ServerSocket(listenPort,0,Inet4Address.getByName(listenAddress)); listeningSocket.setSoTimeout(600); while (!isTimeToBeDone) { try { Socket connectionSocket=listeningSocket.accept(); connectionSocket.shutdownOutput(); } catch ( SocketTimeoutException e) { } } } catch ( Exception e) { } }
Example 80
From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/datacollection/writer/.
Source file: SocketTeeWriter.java

public SocketListenThread(Configuration conf) throws IOException { int portno=conf.getInt("chukwaCollector.tee.port",DEFAULT_PORT); USE_KEEPALIVE=conf.getBoolean("chukwaCollector.tee.keepalive",true); s=new ServerSocket(portno); setDaemon(true); }
Example 81
From project hoop, under directory /hoop-testng/src/main/java/com/cloudera/circus/test/.
Source file: XTest.java

private Server createServer(){ try { String host=InetAddress.getLocalHost().getHostName(); ServerSocket ss=new ServerSocket(0); int port=ss.getLocalPort(); ss.close(); Server server=new Server(0); server.getConnectors()[0].setHost(host); server.getConnectors()[0].setPort(port); return server; } catch ( Exception ex) { throw new RuntimeException("Could not stop embedded servlet container, " + ex.getMessage(),ex); } }
Example 82
From project httpcore, under directory /httpcore/src/examples/org/apache/http/examples/.
Source file: ElementalHttpServer.java

public RequestListenerThread(int port,final String docroot) throws IOException { this.serversocket=new ServerSocket(port); HttpProcessor httpproc=new ImmutableHttpProcessor(new HttpResponseInterceptor[]{new ResponseDate(),new ResponseServer("Test/1.1"),new ResponseContent(),new ResponseConnControl()}); UriHttpRequestHandlerMapper reqistry=new UriHttpRequestHandlerMapper(); reqistry.register("*",new HttpFileHandler(docroot)); this.httpService=new HttpService(httpproc,reqistry); }
Example 83
From project indextank-engine, under directory /src/test/java/com/flaptor/util/.
Source file: TestCase.java

private boolean isSomePortInUse(int[] ports){ for ( int p : ports) { ServerSocket s=null; try { s=new ServerSocket(p); } catch ( IOException e) { System.out.println("Port " + p + " is in use. "+ e); return true; } finally { Execute.close(s); } } return false; }
Example 84
From project IOCipherServer, under directory /src/Acme/Serve/.
Source file: SelectorAcceptor.java

public Socket accept() throws IOException { do { if (readyItor == null) { if (selector.select() > 0) readyItor=selector.selectedKeys().iterator(); else throw new IOException(); } if (readyItor.hasNext()) { SelectionKey key=(SelectionKey)readyItor.next(); readyItor.remove(); if (key.isValid() && key.isAcceptable()) { ServerSocketChannel keyChannel=(ServerSocketChannel)key.channel(); ServerSocket serverSocket=keyChannel.socket(); return serverSocket.accept(); } } else readyItor=null; } while (true); }
Example 85
From project james, under directory /protocols-library/src/test/java/org/apache/james/protocols/lib/.
Source file: PortUtil.java

/** * assigns ports sequentially from the range of test ports * @return port number */ protected synchronized static int getNextNonPrivilegedPort(){ int nextPortCandidate=PORT_LAST_USED; while (true) { try { nextPortCandidate++; if (PORT_LAST_USED == nextPortCandidate) throw new RuntimeException("no free port found"); if (nextPortCandidate > PORT_RANGE_END) nextPortCandidate=PORT_RANGE_START; ServerSocket ss; ss=new ServerSocket(nextPortCandidate); ss.setReuseAddress(true); ss.close(); break; } catch ( IOException e) { e.printStackTrace(); continue; } } PORT_LAST_USED=nextPortCandidate; return PORT_LAST_USED; }
Example 86
public void start() throws InterruptedException { running=true; ServerSocket serverSocket=null; World gameWorld=new World(); try { display("Starting server..."); serverSocket=new ServerSocket(); serverSocket.bind(new InetSocketAddress("localhost",port)); while (running) { display("Waiting for incoming connections..."); Socket socket=null; try { socket=serverSocket.accept(); } catch ( IOException e) { e.printStackTrace(); } ClientThread ct=new ClientThread(socket,sc,this); clientList.put(socket.toString(),ct); ct.start(); listUsers(); } serverSocket.close(); Iterator<Entry<String,ClientThread>> iterator=clientList.entrySet().iterator(); while (iterator.hasNext()) { ClientThread t=(ClientThread)iterator.next(); t.close(); } } catch ( IOException e) { display("Exception starting server" + e); e.printStackTrace(); } }
Example 87
public static void main(String[] args){ Properties p=System.getProperties(); TNC tnc=new TNC(p); int port=8000; try { port=Integer.parseInt(p.getProperty("port","8000").trim()); } catch ( Exception e) { System.err.println("Exception parsing port: " + e.getMessage()); } ServerSocket ss=null; try { ss=new ServerSocket(port); } catch ( IOException ssioe) { System.err.printf("Failed to create server socket: %s\n",ssioe.getMessage()); System.exit(1); } while (true) { Socket s=null; try { s=ss.accept(); } catch ( IOException accepte) { System.err.printf("Failed to create server socket: %s\n",accepte.getMessage()); System.exit(1); } tnc.setSocket(s); tnc.start(); tnc.fromHost(); } }
Example 88
From project jetty-maven-plugin, under directory /src/main/java/org/mortbay/jetty/plugin/.
Source file: Monitor.java

public Monitor(int port,String key,Server[] servers,boolean kill) throws UnknownHostException, IOException { if (port <= 0) throw new IllegalStateException("Bad stop port"); if (key == null) throw new IllegalStateException("Bad stop key"); _key=key; _servers=servers; _kill=kill; setDaemon(true); setName("StopJettyPluginMonitor"); _serverSocket=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1")); _serverSocket.setReuseAddress(true); }
Example 89
From project accent, under directory /src/test/java/net/lshift/accent/.
Source file: ControlledConnectionProxy.java

public void run(){ try { this.inServer=new ServerSocket(listenPort); inServer.setReuseAddress(true); this.inSock=inServer.accept(); this.outSock=new Socket(host,port); DataInputStream iis=new DataInputStream(this.inSock.getInputStream()); DataOutputStream ios=new DataOutputStream(this.inSock.getOutputStream()); DataInputStream ois=new DataInputStream(this.outSock.getInputStream()); DataOutputStream oos=new DataOutputStream(this.outSock.getOutputStream()); byte[] handshake=new byte[8]; iis.readFully(handshake); oos.write(handshake); BlockingCell<Exception> wio=new BlockingCell<Exception>(); new Thread(new DirectionHandler(wio,true,iis,oos)).start(); new Thread(new DirectionHandler(wio,false,ois,ios)).start(); waitAndLogException(wio); } catch ( Exception e) { reportAndLogNonNullException(e); } finally { try { if (this.inSock != null) this.inSock.close(); } catch ( Exception e) { logException(e); } try { if (this.outSock != null) this.outSock.close(); } catch ( Exception e) { logException(e); } this.reportEnd.setIfUnset(null); } }
Example 90
From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.
Source file: TransformListener.java

public static synchronized boolean initialize(Retransformer retransformer,String hostname,Integer port){ if (theTransformListener == null) { try { if (hostname == null) { hostname=DEFAULT_HOST; } if (port == null) { port=Integer.valueOf(DEFAULT_PORT); } theServerSocket=new ServerSocket(); theServerSocket.bind(new InetSocketAddress(hostname,port.intValue())); if (Transformer.isVerbose()) { System.out.println("TransformListener() : accepting requests on " + hostname + ":"+ port); } } catch ( IOException e) { System.out.println("TransformListener() : unexpected exception opening server socket " + e); e.printStackTrace(); return false; } theTransformListener=new TransformListener(retransformer); theTransformListener.start(); } return true; }
Example 91
From project droidtv, under directory /src/com/chrulri/droidtv/.
Source file: StreamActivity.java

/** * @param channelconfig * @return channel name */ private String startStream(String channelconfig){ try { Log.d(TAG,">>> startStream(" + channelconfig + ")"); try { removeSocketFile(); File configFile=new File(getCacheDir(),DVBLAST_CONFIG_FILENAME); PrintWriter writer=new PrintWriter(configFile); String[] params=channelconfig.split(":"); if (params.length != 3) { throw new IOException("invalid DVB params count[" + params.length + "]"); } String name=params[0]; int freq=tryParseInt(params[1],"frequency"); int sid=tryParseInt(params[2],"service ID"); writer.println(String.format(DVBLAST_CONFIG_CONTENT,sid)); writer.close(); Log.d(TAG,"dvblast(" + configFile + ","+ freq+ ")"); mUdpSocket=new DatagramSocket(UDP_PORT,Inet4Address.getByName(UDP_IP)); mUdpSocket.setSoTimeout(1000); mHttpSocket=new ServerSocket(HTTP_PORT,10,Inet4Address.getByName(HTTP_IP)); mStreamTask=new AsyncStreamTask(); mStreamTask.execute(); mDvblastTask=new AsyncDvblastTask(configFile,freq); mDvblastTask.execute(); mDvblastCtlTask=new AsyncDvblastCtlTask(); mDvblastCtlTask.execute(); return name; } catch ( IOException e) { Log.e(TAG,"starting stream failed",e); ErrorUtils.error(this,"failed to start streaming",e); return null; } } finally { Log.d(TAG,"<<< startStream"); } }
Example 92
From project eclim, under directory /org.eclim/java/com/martiansoftware/nailgun/.
Source file: NGServer.java

/** * Listens for new connections and launches NGSession threads to process them. */ public void run(){ running=true; NGSession sessionOnDeck=null; originalSecurityManager=System.getSecurityManager(); System.setSecurityManager(new NGSecurityManager(originalSecurityManager)); if (captureSystemStreams) { synchronized (System.in) { if (!(System.in instanceof ThreadLocalInputStream)) { System.setIn(new ThreadLocalInputStream(in)); System.setOut(new ThreadLocalPrintStream(out)); System.setErr(new ThreadLocalPrintStream(err)); capturedSystemStreams=true; } } } try { if (addr == null) { serversocket=new ServerSocket(port); } else { serversocket=new ServerSocket(port,0,addr); } while (!shutdown) { sessionOnDeck=sessionPool.take(); Socket socket=serversocket.accept(); sessionOnDeck.run(socket); } } catch ( Throwable t) { if (!shutdown) { throw new RuntimeException(t); } } if (sessionOnDeck != null) { sessionOnDeck.shutdown(); } running=false; }
Example 93
public void initialize() throws Exception { String s=Config.GAME_SERVER_HOST_NAME; System.out.println("================================================="); System.out.println(" L1J-En Server Starting"); System.out.println("================================================="); _port=Config.GAME_SERVER_PORT; if (!"*".equals(s)) { InetAddress inetaddress=InetAddress.getByName(s); inetaddress.getHostAddress(); _serverSocket=new ServerSocket(_port,50,inetaddress); System.out.println("Login Server ready on " + (inetaddress == null ? "Port" : inetaddress.getHostAddress()) + ":"+ _port); } else { _serverSocket=new ServerSocket(_port); System.out.println("Port " + _port + " opened"); } MpBugTest mpbug=new MpBugTest(); mpbug.initialize(); SkillTable.initialize(); GameServerThread.getInstance(); Runtime.getRuntime().addShutdownHook(Shutdown.getInstance()); this.start(); }
Example 94
EditServer(String portFile,FreeMindMain pFrame){ super("FreeMind server daemon [" + portFile + "]"); mFrame=pFrame; if (logger == null) { logger=freemind.main.Resources.getInstance().getLogger(this.getClass().getName()); } setDaemon(true); this.portFile=portFile; try { if (Tools.isUnix()) { new File(portFile).createNewFile(); Tools.setPermissions(portFile,0600); } socket=new ServerSocket(0,2,InetAddress.getByName("127.0.0.1")); authKey=new Random().nextInt(Integer.MAX_VALUE); int port=socket.getLocalPort(); FileWriter out=new FileWriter(portFile); try { out.write("b\n"); out.write(String.valueOf(port)); out.write("\n"); out.write(String.valueOf(authKey)); out.write("\n"); } finally { out.close(); } ok=true; logger.info("FreeMind server started on port " + socket.getLocalPort()); logger.info("Authorization key is " + authKey); } catch ( IOException io) { logger.info("" + io); } }
Example 95
From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.
Source file: ViewServer.java

/** * Main server loop. */ public void run(){ try { mServer=new ServerSocket(mPort,VIEW_SERVER_MAX_CONNECTIONS,InetAddress.getLocalHost()); } catch ( Exception e) { Log.w(LOG_TAG,"Starting ServerSocket error: ",e); } while (Thread.currentThread() == mThread) { try { Socket client=mServer.accept(); if (mThreadPool != null) { mThreadPool.submit(new ViewServerWorker(client)); } else { try { client.close(); } catch ( IOException e) { e.printStackTrace(); } } } catch ( Exception e) { Log.w(LOG_TAG,"Connection error: ",e); } } }
Example 96
From project geronimo-xbean, under directory /xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/.
Source file: TelnetDaemon.java

public void start() throws Exception { synchronized (this) { if (!stop) return; stop=false; try { serverSocket=new ServerSocket(port,20); Thread d=new Thread(this); d.setName("service.shell@" + d.hashCode()); d.setDaemon(true); d.start(); } catch ( Exception e) { throw new Exception("Service failed to start.",e); } } }
Example 97
From project grid-goggles, under directory /Dependent Libraries/oscP5/src/netP5/.
Source file: AbstractTcpServer.java

protected void init(){ _myBanList=new Vector(); _myServerSocket=null; _myTcpClients=new Vector(); try { Thread.sleep(1000); } catch ( InterruptedException iex) { Logger.printError("TcpServer.start()","TcpServer sleep interuption " + iex); return; } try { _myServerSocket=new ServerSocket(_myPort); } catch ( IOException e) { Logger.printError("TcpServer.start()","TcpServer io Exception " + e); return; } _myThread=new Thread(this); _myThread.start(); Logger.printProcess("TcpServer","ServerSocket started @ " + _myPort); }
Example 98
From project HMS, under directory /common/src/main/java/org/apache/hms/common/util/.
Source file: PidFile.java

public void init(int port) throws IOException { String pidLong=ManagementFactory.getRuntimeMXBean().getName(); String[] items=pidLong.split("@"); String pid=items[0]; String chukwaPath=System.getProperty("HMS_HOME"); StringBuffer pidFilesb=new StringBuffer(); String pidDir=System.getenv("HMS_PID_DIR"); if (pidDir == null) { pidDir=chukwaPath + File.separator + "var"+ File.separator+ "run"; } pidFilesb.append(pidDir).append(File.separator).append(name).append(".pid"); try { serverSocket=new ServerSocket(port); File existsFile=new File(pidDir); if (!existsFile.exists()) { boolean success=(new File(pidDir)).mkdirs(); if (!success) { throw (new IOException()); } } File pidFile=new File(pidFilesb.toString()); pidFileOutput=new FileOutputStream(pidFile); pidFileOutput.write(pid.getBytes()); pidFileOutput.flush(); log.debug("Initlization succeeded..."); } catch ( IOException ex) { System.out.println("Initialization failed: can not write pid file to " + pidFilesb); log.error("Initialization failed..."); log.error(ex.getMessage()); System.exit(-1); throw ex; } }
Example 99
From project ib-ruby, under directory /misc/IBController 2-9-0/src/ibcontroller/.
Source file: IBControllerServer.java

private boolean createSocket(){ int port=Settings.getInt("IbControllerPort",7462); int backlog=5; String bindaddr=null; try { bindaddr=Settings.getString("IbBindAddress",""); if (bindaddr != null && bindaddr.length() > 0) { mSocket=new ServerSocket(port,backlog,InetAddress.getByName(bindaddr)); } else { bindaddr=InetAddress.getLocalHost().toString(); mSocket=new ServerSocket(port,backlog,InetAddress.getLocalHost()); } Utils.logToConsole("IBControllerServer listening on address: " + bindaddr + " port: "+ java.lang.String.valueOf(port)); } catch ( IOException e) { System.err.println("IBController: exception:\n" + e.toString()); Utils.logToConsole("IBControllerServer failed to create socket"); mSocket=null; mQuitting=true; return false; } return true; }
Example 100
From project jamod, under directory /src/main/java/net/wimpi/modbus/net/.
Source file: ModbusTCPListener.java

/** * Accepts incoming connections and handles then with <tt>TCPConnectionHandler</tt> instances. */ public void run(){ try { m_ServerSocket=new ServerSocket(m_Port,m_FloodProtection,m_Address); if (Modbus.debug) System.out.println("Listenening to " + m_ServerSocket.toString() + "(Port "+ m_Port+ ")"); do { Socket incoming=m_ServerSocket.accept(); if (Modbus.debug) System.out.println("Making new connection " + incoming.toString()); if (m_Listening) { m_ThreadPool.execute(new TCPConnectionHandler(new TCPSlaveConnection(incoming))); count(); } else { incoming.close(); } } while (m_Listening); } catch ( SocketException iex) { if (!m_Listening) { return; } else { iex.printStackTrace(); } } catch ( IOException e) { } }
Example 101
From project java-cas-client, under directory /cas-client-core/src/test/java/org/jasig/cas/client/.
Source file: PublicTestHttpServer.java

public void run(){ try { this.server=new ServerSocket(this.port); System.out.println("Accepting connections on port " + server.getLocalPort()); while (true) { Socket connection=null; try { connection=server.accept(); final OutputStream out=new BufferedOutputStream(connection.getOutputStream()); final InputStream in=new BufferedInputStream(connection.getInputStream()); final StringBuffer request=new StringBuffer(80); while (true) { int c=in.read(); if (c == '\r' || c == '\n' || c == -1) break; request.append((char)c); } if (request.toString().startsWith("STOP")) { connection.close(); break; } if (request.toString().indexOf("HTTP/") != -1) { out.write(this.header); } out.write(this.content); out.flush(); } catch ( final IOException e) { } finally { if (connection != null) connection.close(); } } } catch ( final IOException e) { System.err.println("Could not start server. Port Occupied"); } }
Example 102
From project jetty-project, under directory /jetty-maven-plugin/src/main/java/org/mortbay/jetty/plugin/.
Source file: Monitor.java

public Monitor(int port,String key,Server[] servers,boolean kill) throws UnknownHostException, IOException { if (port <= 0) throw new IllegalStateException("Bad stop port"); if (key == null) throw new IllegalStateException("Bad stop key"); _key=key; _servers=servers; _kill=kill; setDaemon(true); setName("StopJettyPluginMonitor"); InetSocketAddress address=new InetSocketAddress("127.0.0.1",port); _serverSocket=new ServerSocket(); _serverSocket.setReuseAddress(true); try { _serverSocket.bind(address,1); } catch ( IOException x) { System.out.println("Error binding to stop port 127.0.0.1:" + port); throw x; } }
Example 103
From project ardverk-commons, under directory /src/main/java/org/ardverk/io/.
Source file: IoUtils.java

/** * Closes the given {@code Object}. Returns {@code true} on successand {@code false} on failure. All {@link IOException}s will be caught and no error will be thrown if the Object isn't any of the supported types. * @see Closeable * @see #close(Closeable) * @see AutoCloseable * @see #close(AutoCloseable) * @see Socket * @see #close(Socket) * @see ServerSocket * @see #close(ServerSocket) * @see DatagramSocket * @see #close(DatagramSocket) * @see AtomicReference * @see #close(AtomicReference) */ public static boolean close(Object o){ if (o instanceof Closeable) { return close((Closeable)o); } else if (o instanceof AutoCloseable) { return close((AutoCloseable)o); } else if (o instanceof Socket) { return close((Socket)o); } else if (o instanceof ServerSocket) { return close((ServerSocket)o); } else if (o instanceof DatagramSocket) { return close((DatagramSocket)o); } else if (o instanceof AtomicReference<?>) { return close(((AtomicReference<?>)o)); } return false; }
Example 104
From project BHT-FPA, under directory /patterns-codebeispiele/de.bht.fpa.examples.proxypattern/de.bht.fpa.examples.proxypattern.coffemachine.proxy/src/de/bht/fpa/proxypattern/coffemachine/proxy/.
Source file: CoffeMachineRemoteServiceDecorator.java

public synchronized void connect(){ new Thread(){ @Override public void run(){ try { s=new ServerSocket(12345); while (s != null) { System.out.println(getClass().getName() + " Waiting for connections ..."); handleClient(s.accept()); } } catch ( IOException e) { e.printStackTrace(); } } } .start(); }
Example 105
From project cas, under directory /cas-server-support-x509/src/test/java/org/jasig/cas/adaptors/x509/util/.
Source file: MockWebServer.java

/** * Creates a new server that listens for requests on the given port and serves the given resource for all requests. * @param port Server listening port. * @param resource Resource to serve. * @param contentType MIME content type of resource to serve. */ public MockWebServer(final int port,final Resource resource,final String contentType){ try { this.worker=new Worker(new ServerSocket(port),resource,contentType); } catch ( IOException e) { throw new RuntimeException("Cannot create Web server",e); } }
Example 106
public synchronized void startREPLServer() throws CoreException { if (ackREPLServer == null) { try { Var startServer=BundleUtils.requireAndGetVar(getBundle().getSymbolicName(),"clojure.tools.nrepl.server/start-server"); Object defaultHandler=BundleUtils.requireAndGetVar(getBundle().getSymbolicName(),"clojure.tools.nrepl.server/default-handler").invoke(); Object handler=BundleUtils.requireAndGetVar(getBundle().getSymbolicName(),"clojure.tools.nrepl.ack/handle-ack").invoke(defaultHandler); ackREPLServer=(ServerSocket)((Map)startServer.invoke(Keyword.intern("handler"),handler)).get(Keyword.intern("server-socket")); CCWPlugin.log("Started ccw nREPL server: nrepl://localhost:" + ackREPLServer.getLocalPort()); } catch ( Exception e) { CCWPlugin.logError("Could not start plugin-hosted REPL server",e); throw new CoreException(createErrorStatus("Could not start plugin-hosted REPL server",e)); } } }
Example 107
From project gatein-common, under directory /common/src/test/java/org/gatein/common/net/.
Source file: AbstractSynchronizedServer.java

protected void run(ServerSocket server) throws Exception { synchronized (lock) { b.set(1); lock.notifyAll(); } log.debug("Ready for accept"); try { doServer(server); } catch ( Throwable throwable) { failure=throwable; } synchronized (lock) { lock.wait(); } log.debug("Shutting down"); }