List of usage examples for java.net ServerSocket accept
public Socket accept() throws IOException
From source file:org.apache.tomcat.util.net.jsse.JSSESocketFactory.java
public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null;/*from w w w . j a v a2 s . com*/ try { asock = (SSLSocket) socket.accept(); asock.setNeedClientAuth(clientAuth); } catch (SSLException e) { throw new SocketException("SSL handshake error" + e.toString()); } return asock; }
From source file:at.sti2.sparkwave.ServerSocketThread.java
/** * TCP/IP Sparkwave Network Server// w w w.jav a 2 s.com */ public void run() { try { //Open TCP/IP Server socket ServerSocket server = new ServerSocket(configuration.getPort()); logger.info("Server: " + server); while (!Thread.interrupted()) { logger.info("Waiting for connection..."); Socket sock = server.accept(); logger.info("Connected: " + sock); //TODO Not every connection should cause a rebuild of the plugin chain. Should work with arbitrary many connections and failure resistent. re-use plugin threads and parser threads. InputStream socketStreamIn = sock.getInputStream(); // PreProcessing Plugins to be loaded if (configuration.getPPPluginsConfig().size() == 2) { //TODO support arbitrary many plugins // Wiring: socketStreamIn --> (Plugin1) --> PipeOut1 --> PipeIn1 final PipedOutputStream pipeOut1 = new PipedOutputStream(); final PipedInputStream pipeIn1 = new PipedInputStream(pipeOut1); // Wiring: PipeIn1 --> (Plugin2) --> PipeOut2 --> PipeIn2 final PipedOutputStream pipeOut2 = new PipedOutputStream(); final PipedInputStream pipeIn2 = new PipedInputStream(pipeOut2); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // plugin configuration PPPluginConfig pluginConfig1 = configuration.getPPPluginsConfig().get(0); PreProcess plugin1 = instantiateAndConfigurePlugin(pluginConfig1, socketStreamIn, pipeOut1); PPPluginConfig pluginConfig2 = configuration.getPPPluginsConfig().get(1); PreProcess plugin2 = instantiateAndConfigurePlugin(pluginConfig2, pipeIn1, pipeOut2); // N3 Parser StreamParserThread sparkStreamParserThread = new StreamParserThread(pipeIn2, queues); // kick-off pre-process sparkwaveParserExecutor.execute(plugin1); sparkwaveParserExecutor.execute(plugin2); // kick-off parser sparkwaveParserExecutor.execute(sparkStreamParserThread); } else { StreamParserThread sparkStreamParserThread = new StreamParserThread(socketStreamIn, queues); // kick-off parser sparkwaveParserExecutor.execute(sparkStreamParserThread); } } } catch (Exception e) { logger.error(e.getMessage()); } finally { } }
From source file:com.lithium.flow.vault.AgentServer.java
public AgentServer(@Nonnull Config config) throws IOException { checkNotNull(config);//from w w w . j a v a 2 s .c o m ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(System.in, baos); byte[] bytes = baos.toByteArray(); ServerSocket server = new ServerSocket(config.getInt("agent.port"), -1, InetAddress.getByName(null)); long endTime = System.currentTimeMillis() + config.getTime("agent.maximumTime", "1d"); long inactiveTime = config.getTime("agent.inactiveTime", "8h"); AtomicLong lastTime = new AtomicLong(System.currentTimeMillis()); new LoopThread(() -> { try { Socket socket = server.accept(); log.info("accepted connection: {}", socket); try (OutputStream out = socket.getOutputStream()) { IOUtils.copy(new ByteArrayInputStream(bytes), out); } } catch (IOException e) { // } lastTime.set(System.currentTimeMillis()); }); new LoopThread(1000, () -> { long time = System.currentTimeMillis(); if (time > endTime) { log.info("maximum time reached"); System.exit(0); } if (time > lastTime.get() + inactiveTime) { log.info("inactive time reached"); System.exit(0); } }); log.info("started agent on port {}", server.getLocalPort()); Sleep.forever(); }
From source file:org.apache.servicemix.http.ProviderEndpointTest.java
public void testSendProblemWithServerDying() throws Exception { HttpComponent http = new HttpComponent(); HttpSoapProviderEndpoint ep1 = new HttpSoapProviderEndpoint(); ep1.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService")); ep1.setEndpoint("soap"); ep1.setWsdl(new ClassPathResource("person.wsdl")); ep1.setValidateWsdl(false); // TODO: Soap 1.2 not handled yet ep1.setUseJbiWrapper(true);//from w w w . j ava2 s . com http.addEndpoint(ep1); container.activateComponent(http, "http"); container.start(); new Thread() { public void run() { ServerSocket ss = null; try { ss = new ServerSocket(8192); Socket s = ss.accept(); Thread.sleep(50); s.close(); } catch (Throwable t) { t.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); ServiceMixClient client = new DefaultServiceMixClient(container); InOut me = client.createInOutExchange(); me.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService")); me.setOperation(new QName("http://servicemix.apache.org/samples/wsdl-first", "GetPerson")); me.getInMessage().setContent( new StringSource("<jbi:message xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\"" + " xmlns:msg=\"http://servicemix.apache.org/samples/wsdl-first/types\" " + " name=\"Hello\" " + " type=\"msg:HelloRequest\" " + " version=\"1.0\">" + " <jbi:part>" + " <msg:GetPerson><msg:personId>id</msg:personId></msg:GetPerson>" + " </jbi:part>" + "</jbi:message>")); client.sendSync(me); assertEquals(ExchangeStatus.ERROR, me.getStatus()); }
From source file:hudson.gridmaven.gridlayer.PluginImpl.java
/** * Compute the host name that Hadoop nodes can be used to talk to Name node. * * <p>// w ww. j a v a 2s.c om * We prefer to use {@link Hudson#getRootUrl()}, except we have to watch out for a possibility * that it points to a front end (like apache, router with port-forwarding, etc.), and if that is the case, * use some heuristics to find out a usable host name. * * TODO: move this to {@code Hudson.toComputer().getHostName()}. */ String getMasterHostName() throws IOException, InterruptedException { // check if rootURL is reliable Hudson h = Hudson.getInstance(); String rootUrl = h.getRootUrl(); if (rootUrl == null) { // the only option is to auto-detect. String real = h.toComputer().getHostName(); LOGGER.fine("Hudson root URL isn't configured. Using " + real + " instead"); return real; } // according to Hudson's setting, this is the host name that we can use to connect to master, // at least for HTTP. See if we can connect to the arbitrary port in this way. final String hostName = new URL(rootUrl).getHost(); final ServerSocket ss = new ServerSocket(0); Thread t = new Thread() { @Override public void run() { try { ss.accept(); } catch (IOException e) { // shouldn't happen LOGGER.log(Level.INFO, "Failed to accept", e); } finally { try { ss.close(); } catch (IOException e) { // ignore } } } }; t.start(); try { Socket s = new Socket(); s.connect(new InetSocketAddress(hostName, ss.getLocalPort()), 1000); s.close(); // yep, it worked return hostName; } catch (IOException e) { // no it didn't String real = h.toComputer().getHostName(); LOGGER.fine("Hudson root URL " + rootUrl + " looks like a front end. Using " + real + " instead"); return real; } }
From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java
public void run() { ServerSocket serverSocket = null; Socket connectionSocket = null; try {/*from w w w .j a v a2 s . c o m*/ log.info("Trying to bind to localhost on port " + Integer.toString(port) + "..."); serverSocket = new ServerSocket(port); log.info("Running Simple WebServer!\n"); connectionSocket = serverSocket.accept(); connectionSocket.setSoTimeout(30000); //go in a infinite loop, wait for connections, process request, send response while (running) { log.info("\nReady, Waiting for requests...\n"); try { //this call waits/blocks until someone connects to the port we BufferedReader input; if (!connectionSocket.isClosed()) { InetAddress client = connectionSocket.getInetAddress(); log.info(client.getHostName() + " connected to server.\n"); input = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset())); if (input.ready()) { DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream()); httpHandler(input, output); } } //Prepare a outputStream. This will be used sending back our response //(header + requested file) to the client. } catch (Exception e) { //catch any errors, and print them log.info("\nError:" + e.getMessage()); running = false; } } } catch (Exception e) { log.error("\nFatal Error:" + e.getMessage()); running = false; } finally { try { if (connectionSocket != null) { connectionSocket.close(); serverSocket.close(); } } catch (IOException e) { log.error("Error while shutting down server sockets", e); } } }
From source file:de.xwic.appkit.core.cluster.impl.InboundConnectionHandler.java
@Override public void run() { ServerSocket srvSocket; try {/*from w w w . j a v a 2 s .c o m*/ srvSocket = new ServerSocket(port); } catch (IOException e) { log.error("Can not open server socket", e); return; // exit } int conHandlerCount = 0; int errCount = 0; long lastErr = 0; while (true) { try { Socket socket = srvSocket.accept(); log.debug("Accepted connection from " + socket.getInetAddress().getHostAddress()); ClientHandler ch = new ClientHandler(cluster, socket); Thread t = new Thread(ch, "ConnectionHandler-" + socket.getInetAddress().getHostAddress() + "-" + conHandlerCount++); t.setDaemon(true); // launch as a Deamon t.start(); } catch (IOException e) { log.error("Error accepting incoming connection...", e); if ((System.currentTimeMillis() - lastErr) < 3000) { // the last error was just 3 seconds ago errCount++; if (errCount > 100) { log.error("More than 100 errors occured within the last 3 seconds. Giving up."); break; // break the loop } } else { errCount = 0; } lastErr = System.currentTimeMillis(); } } }
From source file:org.openmrs.module.mirebalais.integration.MirthIT.java
private String listenForResults() throws IOException { ServerSocket listener = new ServerSocket(6660); // TODO: store this port in a global property? listener.setSoTimeout(20000); // don't wait more than 20 seconds for an incoming connection Socket mirthConnection = listener.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(mirthConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line;/*from ww w . ja v a2s.com*/ while ((line = reader.readLine()) != null) { sb.append(line); } // TODO: need an acknowledgement? mirthConnection.close(); listener.close(); return sb.toString(); }
From source file:org.eredlab.g4.ccl.net.bsd.RExecClient.java
InputStream _createErrorStream() throws IOException { ServerSocket server; Socket socket;/*from w w w. ja v a 2s . co m*/ server = _socketFactory_.createServerSocket(0, 1, getLocalAddress()); _output_.write(Integer.toString(server.getLocalPort()).getBytes()); _output_.write('\0'); _output_.flush(); socket = server.accept(); server.close(); if (__remoteVerificationEnabled && !verifyRemote(socket)) { socket.close(); throw new IOException("Security violation: unexpected connection attempt by " + socket.getInetAddress().getHostAddress()); } return (new SocketInputStream(socket, socket.getInputStream())); }
From source file:srvmonitor.thMonitorSocket.java
@Override public void run() { try {// w w w . j a va2 s. c om logger.info("Starting Listener Thread Monitor Server port: " + gDatos.getServerInfo().getSrvPort()); ServerSocket skServidor = new ServerSocket(gDatos.getServerInfo().getSrvPort()); String inputData; String outputData; String dRequest; String dAuth; JSONObject jHeader; JSONObject jData; int result; while (isSocketActive) { Socket skCliente = skServidor.accept(); InputStream inpStr = skCliente.getInputStream(); DataInputStream dataInput = new DataInputStream(inpStr); //Espera Entrada // try { inputData = dataInput.readUTF(); logger.info("Recibiendo TX: " + inputData); jHeader = new JSONObject(inputData); jData = jHeader.getJSONObject("data"); dAuth = jHeader.getString("auth"); dRequest = jHeader.getString("request"); if (dAuth.equals(gDatos.getServerInfo().getAuthKey())) { switch (dRequest) { case "keepAlive": result = gSub.updateStatusService(jData.getJSONObject("ServiceStatus")); if (result == 0) { outputData = gSub .sendAssignedProc(jData.getJSONObject("ServiceStatus").getString("srvID")); } else { outputData = gSub.sendError(10); } break; case "getDate": outputData = gSub.sendDate(); break; case "getStatus": logger.info("ejecutando ... getStatusServices"); outputData = gSub.sendStatusServices(); break; case "putExecOSP": gSub.putExecOSP(inputData); outputData = gSub.sendOkTX(); break; case "sendPing": outputData = "OK"; break; default: outputData = gSub.sendError(99, "Error Desconocido..."); } } else { outputData = gSub.sendError(60); } } catch (IOException | JSONException e) { outputData = gSub.sendError(90); } //Envia Respuesta // OutputStream outStr = skCliente.getOutputStream(); DataOutputStream dataOutput = new DataOutputStream(outStr); logger.debug("Enviando respuesta: " + outputData); if (outputData == null) { dataOutput.writeUTF("{}"); } else { dataOutput.writeUTF(outputData); } //Cierra Todas las conexiones // inpStr.close(); dataInput.close(); skCliente.close(); } } catch (NumberFormatException | IOException e) { logger.error(e.getMessage()); } }