List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket(int port) throws IOException
From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java
@Override public void run() { Socket socket = null;/*w ww. j a v a 2 s .c om*/ try { if (myPrintOutput) { System.out.println("Opening server socket on port " + 10201); } ServerSocket serverSocket = new ServerSocket(10201); socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); inputStream = new BufferedInputStream(inputStream); MinLLPReader minLLPReader = new MinLLPReader(inputStream); Socket outSocket = null; if (myPrintOutput) { System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress()); } for (int i = 0; i < myIterations; i++) { String messageText; do { messageText = minLLPReader.getMessage(); Thread.sleep(250); } while (messageText == null); if (myPrintOutput) { System.out.println("Received message:\r\n" + messageText + "\r\n"); } MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH"); String controlId = inboundHeader.getMessageControlID().encode(); if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) { Message replyAck = DefaultApplication.makeACK(inboundHeader); new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck)); } else { System.out.println("Ignoring message with control ID " + controlId); } for (Map.Entry<String, String> next : mySubstitutions.entrySet()) { messageText = messageText.replace(next.getKey(), next.getValue()); } if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) { outSocket.close(); outSocket = null; } if (outSocket == null) { if (myPrintOutput) { System.out.println("Opening outbound connection to port " + 10200); } outSocket = new Socket(); outSocket.connect(new InetSocketAddress("localhost", 10200)); } if (myPrintOutput) { System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n" + messageText + "\r\n"); } new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText); new MinLLPReader(outSocket.getInputStream()).getMessage(); } serverSocket.close(); socket.close(); myStopped = true; } catch (Exception e) { myStopped = true; e.printStackTrace(); } }
From source file:TalkServerThread.java
public void start() { ServerSocket serverRSocket = null; int numConnected = 0; try {// w ww . jav a2 s.com serverRSocket = new ServerSocket(0); System.out.println("TalkServer listening on rendezvous port: " + serverRSocket.getLocalPort()); } catch (IOException e) { System.err.println("Server could not create server socket for rendezvous."); return; } while (true) { //Connect to two clients. while (numConnected < 2) { TalkServerThread tst; tst = connectToClient(serverRSocket); if (tst != null) { numConnected++; if (tstList[0] == null) { tstList[0] = tst; } else { tstList[1] = tst; } } } //end while (numConnected < 2) loop if (DEBUG) { try { System.out.println("tst #0 = " + tstList[0]); } catch (Exception e) {} try { System.out.println("tst #1 = " + tstList[1]); } catch (Exception e) {} } //If they're really OK, tell them to start writing. if (everythingIsOK(0) & everythingIsOK(1)) { for (int i = 0; i < 2; i++) { writeToStream("START WRITING!\n----------------------" + "-------------", tstList[i].os); } } else { System.err.println("2 server threads created, but " + "not everything is OK"); } while (numConnected == 2) { if (!everythingIsOK(0)) { if (DEBUG) { System.out.println("Applet #0 is hosed; disconnecting."); } numConnected--; cleanup(tstList[0]); tstList[0] = null; } if (!everythingIsOK(1)) { if (DEBUG) { System.out.println("Applet #1 is hosed; disconnecting."); } numConnected--; cleanup(tstList[1]); tstList[1] = null; } try { Thread.sleep(1000); } catch (InterruptedException e) { } } //end while(numConnected==2) loop if (DEBUG) { try { System.out.println("Number of connections = " + numConnected); System.out.println("tst #0 = " + tstList[0]); System.out.println("tst #1 = " + tstList[1]); } catch (Exception e) {} } } //end while (true) loop }
From source file:net.sourceforge.cobertura.test.util.WebappServer.java
public WebappServer(File webappServerDir, boolean tomcat) { this.tomcat = tomcat; ServerSocket s;/*from www. ja va 2 s.c o m*/ try { s = new ServerSocket(0); webappPort = s.getLocalPort(); s.close(); s = new ServerSocket(0); stopPort = s.getLocalPort(); s.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.lib.OpflexConnectionServiceTest.java
private ServerSocket create(int[] ports) throws IOException { for (int port : ports) { try {//from w w w . jav a2 s.c om return new ServerSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found"); }
From source file:com.splout.db.engine.EmbeddedMySQL.java
/** * TODO MySQL Hangs if port is busy, we should perform a timeout in a separate thred. *///from w ww .ja v a 2s . co m @SuppressWarnings({ "unchecked", "rawtypes" }) public void start(boolean deleteFilesIfExist) throws IOException, InterruptedException { if (deleteFilesIfExist && config.residentFolder.exists()) { File pidFile = new File(config.residentFolder, "data/MysqldResource.pid"); if (pidFile.exists()) { // Issue "kill -9" if process is still alive String pid = Files.toString(pidFile, Charset.defaultCharset()); log.info("Killing existing process: " + pid); Runtime.getRuntime().exec("kill -9 " + pid).waitFor(); } log.info("Deleting contents of: " + config.residentFolder); FileUtils.deleteDirectory(config.residentFolder); } log.info("Using config: " + config); MysqldResource mysqldResource = new MysqldResource(config.residentFolder); Map<String, String> database_options = new HashMap(); database_options.put(MysqldResourceI.PORT, Integer.toString(config.port)); database_options.put(MysqldResourceI.INITIALIZE_USER, "true"); database_options.put(MysqldResourceI.INITIALIZE_USER_NAME, config.user); database_options.put(MysqldResourceI.INITIALIZE_PASSWORD, config.pass); database_options.put("innodb-file-per-table", "true"); if (config.customConfig != null) { for (Map.Entry<String, Object> entry : config.customConfig.entrySet()) { database_options.put(entry.getKey(), entry.getValue().toString()); } } log.info("Using the following MySQL Configuration:"); for (Map.Entry<String, String> entry : database_options.entrySet()) { log.info("MySQLConf: " + entry.getKey() + " -> " + entry.getValue()); } // I have to do this checking myself, otherwise in some cases mysqldResource will block undefinitely... try { ServerSocket serverSocket = new ServerSocket(config.port); serverSocket.close(); } catch (IOException e) { throw new RuntimeException("Port already in use: " + config.port); } if (mysqldResource.isRunning()) { throw new RuntimeException("MySQL already running!"); } mysqldResource.start("test-mysqld-thread", database_options); if (!mysqldResource.isRunning()) { throw new RuntimeException("MySQL did not start successfully!"); } log.info("MySQL is running."); resource = mysqldResource; }
From source file:grakn.core.rule.GraknTestServer.java
protected static int findUnusedLocalPort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); }//w w w . java 2 s . c o m }
From source file:de.uni_koblenz.jgralab.utilities.tgraphbrowser.TGraphBrowserServer.java
public TGraphBrowserServer(int port, String path, String maximumFileSize, String maximumWorkspaceSize) throws IOException { if (path == null) { throw new IllegalArgumentException("path must not be null"); }/*from w ww . j a v a2s . c om*/ workspace = path; if ((path != null) && (workspace.startsWith("\"") || workspace.startsWith("'"))) { workspace = workspace.substring(1, workspace.length() - 1); } StateRepository.MAXIMUM_FILE_SIZE = maximumFileSize == null ? null : Long.parseLong(maximumFileSize) * 1024 * 1024; File ws = new File(workspace); StateRepository.MAXIMUM_WORKSPACE_SIZE = maximumWorkspaceSize == null ? ws.getFreeSpace() + ws.getTotalSpace() : Long.parseLong(maximumWorkspaceSize) * 1024 * 1024; _serverSocket = new ServerSocket(port); }
From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java
private static int detectPort() throws IOException { try (final ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); }//from ww w . ja v a2 s. co m }
From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java
@Before public void cleanState() { super.cleanState(); try {/*from www . j a v a2s . c om*/ try (ServerSocket sock = new ServerSocket(0)) { httpServerBaseUri = URI.create(String.format("http://%s:%d/", InetAddressUtils.formatInetAddress(InetAddress.getLoopbackAddress()), sock.getLocalPort())); } final ResourceConfig rc = new ResourceConfig().registerInstances(Sets.newHashSet( new ApiController(factory), new ClusterCleanupController(cluster, factory), new ClusterRepairController(cluster, factory), new ClusterRollingRestartController(cluster, factory), new ClusterBackupController(cluster, factory), new ClusterRestoreController(cluster, factory), new ConfigController(cluster, factory), new LiveEndpointsController(cluster, factory), new NodeController(cluster, factory), new QaReportController(cluster, factory))); httpServer = GrizzlyHttpServerFactory.createHttpServer(httpServerBaseUri, rc); httpServer.start(); } catch (final Exception e) { throw new RuntimeException(e); } }
From source file:com.opentable.etcd.EtcdInstance.java
private static int findPort(int configuredPort) throws IOException { if (configuredPort != 0) { return configuredPort; }/*from w w w . j a v a 2s. co m*/ try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } }