List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket() throws IOException
From source file:org.devtcg.five.server.AbstractHttpServer.java
public AbstractHttpServer() throws IOException { mSocket = new ServerSocket(); mParams = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(mParams, 60000); setDaemon(true);/*from w ww . j ava 2 s . c om*/ setPriority(MIN_PRIORITY); }
From source file:mamo.vanillaVotifier.VotifierServer.java
public synchronized void start() throws IOException { if (isRunning()) { throw new IllegalStateException("Server is already running!"); }/*www.jav a2s. c om*/ notifyListeners(new ServerStartingEvent()); serverSocket = new ServerSocket(); serverSocket.bind(votifier.getConfig().getInetSocketAddress()); running = true; notifyListeners(new ServerStartedEvent()); new Thread(new Runnable() { @Override public void run() { ExecutorService executorService = Executors.newSingleThreadExecutor(); while (isRunning()) { try { final Socket socket = serverSocket.accept(); executorService.execute(new Runnable() { @Override public void run() { try { notifyListeners(new ConnectionEstablishedEvent(socket)); socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("VOTIFIER 2.9\n"); writer.flush(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch. byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair() .getPublic()).getModulus().bitLength() / Byte.SIZE]; in.read(request); // IOException: handled by try/catch. notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request))); request = RsaUtils .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate()) .doFinal(request); // IllegalBlockSizeException: can't happen. String requestString = new String(request); notifyListeners(new DecryptedInputReceivedEvent(socket, requestString)); String[] requestArray = requestString.split("\n"); if ((requestArray.length == 5 || requestArray.length == 6) && requestArray[0].equals("VOTE")) { notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1], requestArray[2], requestArray[3], requestArray[4]))); for (VoteAction voteAction : votifier.getConfig().getVoteActions()) { String[] params = new String[4]; try { for (int i = 0; i < params.length; i++) { params[i] = SubstitutionUtils.applyRegexReplacements( requestArray[i + 1], voteAction.getRegexReplacements()); } } catch (PatternSyntaxException e) { notifyListeners(new RegularExpressionPatternErrorException(e)); params = new String[] { requestArray[1], requestArray[2], requestArray[3], requestArray[4] }; } if (voteAction.getCommandSender() instanceof RconCommandSender) { RconCommandSender commandSender = (RconCommandSender) voteAction .getCommandSender(); StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor( new SimpleEntry<String, Object>("service-name", params[0]), new SimpleEntry<String, Object>("user-name", params[1]), new SimpleEntry<String, Object>("address", params[2]), new SimpleEntry<String, Object>("timestamp", params[3])); for (String command : voteAction.getCommands()) { String theCommand = substitutor.replace(command); notifyListeners(new SendingRconCommandEvent( commandSender.getRconConnection(), theCommand)); try { notifyListeners(new RconCommandResponseEvent( commandSender.getRconConnection(), commandSender .sendCommand(theCommand).getPayload())); } catch (Exception e) { notifyListeners(new RconExceptionEvent( commandSender.getRconConnection(), e)); } } } if (voteAction.getCommandSender() instanceof ShellCommandSender) { ShellCommandSender commandSender = (ShellCommandSender) voteAction .getCommandSender(); HashMap<String, String> environment = new HashMap<String, String>(); environment.put("voteServiceName", params[0]); environment.put("voteUserName", params[1]); environment.put("voteAddress", params[2]); environment.put("voteTimestamp", params[3]); for (String command : voteAction.getCommands()) { notifyListeners(new SendingShellCommandEvent(command)); try { commandSender.sendCommand(command, environment); notifyListeners(new ShellCommandSentEvent()); } catch (Exception e) { notifyListeners(new ShellCommandExceptionEvent(e)); } } } } } else { notifyListeners(new InvalidRequestEvent(socket, requestString)); } } catch (SocketTimeoutException e) { notifyListeners(new ReadTimedOutExceptionEvent(socket, e)); } catch (BadPaddingException e) { notifyListeners(new DecryptInputExceptionEvent(socket, e)); } catch (Exception e) { notifyListeners(new CommunicationExceptionEvent(socket, e)); } try { socket.close(); notifyListeners(new ConnectionClosedEvent(socket)); } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close. notifyListeners(new ConnectionCloseExceptionEvent(socket, e)); } } }); } catch (Exception e) { if (running) { // Show errors only while running, to hide error while stopping. notifyListeners(new ConnectionEstablishExceptionEvent(e)); } } } executorService.shutdown(); if (!executorService.isTerminated()) { notifyListeners(new ServerAwaitingTaskCompletionEvent()); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (Exception e) { // InterruptedException: can't happen. } } notifyListeners(new ServerStoppedEvent()); } }).start(); }
From source file:org.devtcg.five.server.AbstractHttpServer.java
public void rebind(int port) throws IOException { synchronized (this) { mSocket.close();// w w w . j a v a 2 s. co m mSocket = new ServerSocket(); } bind(port); }
From source file:com.yanzhenjie.andserver.DefaultAndServer.java
@Override public void run() { try {// w ww . ja va 2s.com mServerSocket = new ServerSocket(); mServerSocket.setReuseAddress(true); mServerSocket.bind(new InetSocketAddress(mPort)); // HTTP?? BasicHttpProcessor httpProcessor = new BasicHttpProcessor(); httpProcessor.addInterceptor(new ResponseDate()); httpProcessor.addInterceptor(new ResponseServer()); httpProcessor.addInterceptor(new ResponseContent()); httpProcessor.addInterceptor(new ResponseConnControl()); // HTTP Attribute. HttpParams httpParams = new BasicHttpParams(); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "WebServer/1.1"); // Http? HttpRequestHandlerRegistry handlerRegistry = new HttpRequestHandlerRegistry(); for (Map.Entry<String, AndServerRequestHandler> handlerEntry : mRequestHandlerMap.entrySet()) { handlerRegistry.register("/" + handlerEntry.getKey(), new DefaultHttpRequestHandler(handlerEntry.getValue())); } // HTTP? HttpService httpService = new HttpService(httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); httpService.setParams(httpParams); httpService.setHandlerResolver(handlerRegistry); /** * ? */ while (isLoop) { // if (!mServerSocket.isClosed()) { Socket socket = mServerSocket.accept(); DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection(); serverConnection.bind(socket, httpParams); // Dispatch request handler. RequestHandleTask requestTask = new RequestHandleTask(this, httpService, serverConnection); requestTask.setDaemon(true); AndWebUtil.executeRunnable(requestTask); } } } catch (Exception e) { } finally { close(); } }
From source file:org.devtcg.five.util.streaming.LocalHttpServer.java
public void bind(InetSocketAddress addr) throws IOException { mSocket = new ServerSocket(); mSocket.bind(addr);// w ww . j a v a 2s .co m Log.i(TAG, "Bound to port " + mSocket.getLocalPort()); }
From source file:com.kixeye.kixmpp.client.KixmppClientTest.java
@Before public void setUp() throws Exception { domain = UUID.randomUUID().toString().replace("-", ""); username = UUID.randomUUID().toString().replace("-", ""); password = UUID.randomUUID().toString().replace("-", ""); resource = UUID.randomUUID().toString().replace("-", ""); ServerSocket socketServer = new ServerSocket(); socketServer.bind(null);// ww w .ja v a 2s . co m port = socketServer.getLocalPort(); socketServer.close(); StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry(); final Entity adminJID = EntityImpl.parseUnchecked(username + "@" + domain); final AccountManagement accountManagement = (AccountManagement) providerRegistry .retrieve(AccountManagement.class); if (!accountManagement.verifyAccountExists(adminJID)) { accountManagement.addUser(adminJID, password); } TCPEndpoint tcpEndpoint = new TCPEndpoint(); tcpEndpoint.setPort(port); try (InputStream certStream = this.getClass().getResourceAsStream("/bogus_mina_tls.cert")) { server = new XMPPServer(domain); server.addEndpoint(tcpEndpoint); server.setStorageProviderRegistry(providerRegistry); server.setTLSCertificateInfo(certStream, "boguspw"); server.start(); server.addModule(new SoftwareVersionModule()); server.addModule(new EntityTimeModule()); server.addModule(new XmppPingModule()); server.addModule(new InBandRegistrationModule()); server.addModule(new AdhocCommandsModule()); final ServiceAdministrationModule serviceAdministrationModule = new ServiceAdministrationModule(); // unless admin user account with a secure password is added, this will be not become effective serviceAdministrationModule.setAddAdminJIDs(Arrays.asList(adminJID)); server.addModule(serviceAdministrationModule); } }
From source file:com.nesscomputing.httpserver.TestGuiceModule.java
private static int findUnusedPort() throws IOException { int port;/*from w w w.j a v a2 s. c om*/ ServerSocket socket = new ServerSocket(); try { socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } finally { socket.close(); } return port; }
From source file:gov.hhs.fha.nhinc.lift.ClientApp.java
private void startClient() { try {//www . j a v a 2 s .c om String clientIP = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.LIFT_CLIENT_IP); String clientPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.LIFT_CLIENT_PORT); SocketAddress saddr = new InetSocketAddress(clientIP, Integer.parseInt(clientPort)); ServerSocket server = new ServerSocket(); server.bind(saddr); log.debug("Client listening on " + saddr); ClientPropertiesFacade props = new ClientPropertiesService(); ConsumerProxyPropertiesFacade proxyProps = new ConsumerProxyPropertiesFacadeRI(); proxyProps.setTrustStore(); proxyProps.setKeyStoreProperty(); LSTClientManager manager = new LSTClientManager(props, proxyProps); SocketClientManagerController con = new SocketClientManagerController(server, manager); (new Thread(con)).start(); System.out.println("ClientApp started. "); } catch (PropertyAccessException ex) { log.error(ex.getMessage()); } catch (IOException ex) { log.error(ex.getMessage()); } }
From source file:org.devtcg.rojocam.rtsp.AbstractRtspServer.java
public void bind(InetSocketAddress addr) throws IOException { ServerSocket socket = new ServerSocket(); socket.bind(addr);// w w w . j a v a2 s. c o m mSocket = socket; Log.i(TAG, "Bound to port " + mSocket.getLocalPort()); }
From source file:com.nesscomputing.httpserver.TestHttpCompression.java
private static int findUnusedPort() throws IOException { int port;/*from ww w.j a va 2 s. c o m*/ try (ServerSocket socket = new ServerSocket()) { socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } return port; }