List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket(int port) throws IOException
From source file:com.kixeye.relax.AsyncRestClientTest.java
@Before public void setUp() throws Exception { Server server = new ContainerServer(testContainer); connection = new SocketConnection(server); ServerSocket socketServer = new ServerSocket(0); port = socketServer.getLocalPort();//from w w w. j av a2 s.c o m socketServer.close(); connection.connect(new InetSocketAddress(port)); }
From source file:org.wso2.carbon.inbound.endpoint.protocol.hl7.core.InboundHL7IOReactor.java
private static boolean isPortAvailable(int port) { try {//from w w w . j ava 2 s . c om ServerSocket ss = new ServerSocket(port); ss.close(); return true; } catch (IOException e) { return false; } }
From source file:com.clough.android.androiddbviewer.ADBVApplication.java
@Override public void onCreate() { super.onCreate(); // Getting user configured(custom) SQLiteOpenHelper instance. sqliteOpenHelper = getDataBase();//from w w w . j av a2 s . co m // getDataBase() could return a null if (sqliteOpenHelper != null) { // Background operation of creating the server socket. new Thread(new Runnable() { @Override public void run() { try { // Server socket re create when device is being disconnected or // when AndroidDBViewer desktop application is being closed. // Creating server socket will exit when // android application runs in low memory or when // android application being terminated due some reasons. l1: while (flag) { serverSocket = new ServerSocket(1993); socket = serverSocket.accept(); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(socket.getOutputStream(), true); // Keeps a continuous communication between android application and // AndroidDBViewer desktop application through IO streams of the accepted socket connection. // There will be continuous data parsing between desktop application and android application. // Identification of device being disconnected or desktop application being closed will be determined // only when there is a NULL data being received. l2: while (flag) { // Format of the parsing data string is JSON, a content of a 'Data' instance String requestJSONString = br.readLine(); if (requestJSONString == null) { // Received a null response from desktop application, due to disconnecting the // device or closing the AndroidDBViewer desktop application. // Therefore, closing all current connections and streams to re create the server // socket so that desktop application can connect in it's next run. // Device disconnection doesn't produce an IOException. // Also, even after calling // socket.close(), socket.shutdownInput() and socket.shutdownOutput() // within a shutdown hook in desktop application, the socket connection // in this async task always gives // socket.isConnected() as 'true' , // socket.isClosed() as 'false' , // socket.isInputShutdown() as 'false' and // socket.isOutputShutdown() as 'false' . // But, bufferedReader.readLine() starts returning 'null' continuously. // So, inorder to desktop application to connect with the device again, // there should be a ServerSocket waiting to accept a socket connection, in device. closeConnection(); continue l1; } else { // Received a valid response from the desktop application. Data data; try { // Converting received request to a 'Data' instance. data = new Data(new JSONObject(requestJSONString)); int status = data.getStatus(); if (status == Data.CONNECTION_REQUEST) { // Very first request from desktop application to // establish the connection and setting the response as // connection being accepted. data.setStatus(Data.CONNECTION_ACCEPTED); } else if (status == Data.LIVE_CONNECTION) { // When there is no user interaction in desktop application, // data being passed from desktop application to android // application with the status of LIVE_CONNECTION, and the // same data send again to the desktop application from android application, // to notify that connection is still alive. // This exchange won't change until there is a request from // desktop application with a different status. } else if (status == Data.QUERY) { // Requesting to perform a query execution. String result = "No result"; try { // Performing select, insert, delete and update queries. Cursor cursor = sqliteOpenHelper.getWritableDatabase() .rawQuery(data.getQuery(), null); // Flag to identify the firs move of the cursor boolean firstTime = true; int columnCount = 0; // JSONArray to hold the all JSONObjects, created per every row // of the result returned, executing the given query. JSONArray jsonArray = new JSONArray(); // Moving the cursor to the next row of retrieved result // after executing the requested query. while (cursor.moveToNext()) { if (firstTime) { // Column count of the result returned, executing the given query. columnCount = cursor.getColumnCount(); firstTime = false; } // JOSNObject to hold the values of a single row JSONObject jsonObject = new JSONObject(); for (int i = 0; i < columnCount; i++) { int columnType = cursor.getType(i); String columnName = cursor.getColumnName(i); if (columnType == Cursor.FIELD_TYPE_STRING) { jsonObject.put(columnName, cursor.getString(i)); } else if (columnType == Cursor.FIELD_TYPE_BLOB) { jsonObject.put(columnName, cursor.getBlob(i).toString()); } else if (columnType == Cursor.FIELD_TYPE_FLOAT) { jsonObject.put(columnName, String.valueOf(cursor.getFloat(i))); } else if (columnType == Cursor.FIELD_TYPE_INTEGER) { jsonObject.put(columnName, String.valueOf(cursor.getInt(i))); } else if (columnType == Cursor.FIELD_TYPE_NULL) { jsonObject.put(columnName, "NULL"); } else { jsonObject.put(columnName, "invalid type"); } } jsonArray.put(jsonObject); } result = jsonArray.toString(); cursor.close(); } catch (Exception e) { // If SQL error is occurred when executing the requested query, // error content will be the response to the desktop application. StringWriter sw = new StringWriter(); PrintWriter epw = new PrintWriter(sw); e.printStackTrace(epw); result = sw.toString(); epw.close(); sw.close(); } finally { data.setResult(result); } } else if (status == Data.DEVICE_NAME) { // Requesting device information data.setResult(Build.BRAND + " " + Build.MODEL); } else if (status == Data.APPLICATION_ID) { // Requesting application id (package name) data.setResult(getPackageName()); } else if (status == Data.DATABASE_NAME) { // Requesting application database name. // Will provide the database name according // to the SQLiteOpenHelper user provided data.setResult(sqliteOpenHelper.getDatabaseName()); } else { // Unidentified request state. closeConnection(); continue l1; } String responseJSONString = data.toJSON().toString(); pw.println(responseJSONString); } catch (JSONException e) { // Response couldn't convert to a 'Data' instance. // Desktop application will be notified to close the application. closeConnection(); continue l1; } } } } } catch (IOException e) { // Cannot create a server socket. Letting background process to end. } } }).start(); } }
From source file:jhttpp2.Jhttpp2Server.java
public void init() { writeLog("server startup..."); if (serverproperties == null) { log.warn("Server properties should be set prior to init"); }/*from w w w . j av a 2 s . c o m*/ if (dic == null) { log.warn("Server dic should be set prior to calling init"); } if (urlactions == null) { log.warn("url actions should be set prior to init"); } try { listen = new ServerSocket(port); } catch (BindException e_bind_socket) { setErrorMsg("Socket " + port + " is already in use (Another jHTTPp2 proxy running?) " + e_bind_socket.getMessage()); } catch (IOException e_io_socket) { setErrorMsg( "IO Exception while creating server socket on port " + port + ". " + e_io_socket.getMessage()); } if (error) { writeLog(error_msg); return; } }
From source file:info.batey.kafka.unit.KafkaUnit.java
private static int getEphemeralPort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); }// ww w . j a v a2 s . co m }
From source file:org.apache.beam.sdk.io.hadoop.format.HadoopFormatIOElasticTest.java
@BeforeClass public static void startServer() throws NodeValidationException, IOException { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close();/* w w w . j ava2 s. com*/ elasticInMemPort = String.valueOf(port); ElasticEmbeddedServer.startElasticEmbeddedServer(); }
From source file:org.sonatype.nexus.internal.httpclient.HttpClientFactoryImplRemoteTest.java
@Before public void prepare() throws Exception { userAgentChecker = new UserAgentChecker(); try (final ServerSocket ss = new ServerSocket(0)) { port = ss.getLocalPort();//w ww . j a v a 2s .c om } server = new Server(port); server.setHandler(userAgentChecker); server.start(); when(systemStatus.getEditionShort()).thenReturn("OSS"); when(systemStatus.getVersion()).thenReturn("3.0"); final DefaultRemoteConnectionSettings rcs = new DefaultRemoteConnectionSettings(); rcs.setConnectionTimeout(1234); when(globalRemoteStorageContext.getRemoteConnectionSettings()).thenReturn(rcs); when(globalRemoteStorageContext.getRemoteProxySettings()).thenReturn(remoteProxySettings); when(remoteProxySettings.getHttpProxySettings()).thenReturn(remoteHttpProxySettings); when(remoteProxySettings.getHttpsProxySettings()).thenReturn(remoteHttpProxySettings); // jetty acts as proxy when(remoteHttpProxySettings.getHostname()).thenReturn("localhost"); when(remoteHttpProxySettings.getPort()).thenReturn(port); }
From source file:com.emc.ia.sipcreator.testing.xdb.TemporaryXDBResource.java
protected void startListener() { if (port > 0) { try {/* w ww.ja v a 2 s . c om*/ socket = new ServerSocket(port); driver.startListenerThread(socket); } catch (final IOException e) { throw new RuntimeException(e); } } }
From source file:ch.vorburger.mariadb4j.DBConfigurationBuilder.java
protected int detectFreePort() { try {/* ww w. ja va2s . c o m*/ ServerSocket ss = new ServerSocket(0); port = ss.getLocalPort(); ss.setReuseAddress(true); ss.close(); return port; } catch (IOException e) { // This should never happen throw new RuntimeException(e); } }
From source file:com.alibaba.jstorm.yarn.utils.JstormYarnUtils.java
/** * See if a port is available for listening on by trying to listen * on it and seeing if that works or fails. * * @param port port to listen to//w ww .j a va2 s . c o m * @return true if the port was available for listening on */ public static boolean isPortAvailable(int port) { try { ServerSocket socket = new ServerSocket(port); socket.close(); return true; } catch (IOException e) { return false; } }