List of usage examples for java.nio.channels ServerSocketChannel open
public static ServerSocketChannel open() throws IOException
From source file:hudson.TcpSlaveAgentListener.java
/** * @param port/*from w ww . jav a 2 s. co m*/ * Use 0 to choose a random port. */ public TcpSlaveAgentListener(int port) throws IOException { super("TCP agent listener port=" + port); try { serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(port)); } catch (BindException e) { throw (BindException) new BindException( "Failed to listen on port " + port + " because it's already in use.").initCause(e); } this.configuredPort = port; setUncaughtExceptionHandler((t, e) -> { LOGGER.log(Level.SEVERE, "Uncaught exception in TcpSlaveAgentListener " + t + ", attempting to reschedule thread", e); shutdown(); TcpSlaveAgentListenerRescheduler.schedule(t, e); }); LOGGER.log(Level.FINE, "TCP agent listener started on port {0}", getPort()); start(); }
From source file:com.app.services.ExecutorServiceThread.java
public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) { this.serviceList = serviceList; this.serverConfig = serverConfig; this.mbeanServer = mbeanServer; try {/*from w ww .jav a 2 s .co m*/ serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel .bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverConfig.getServicesport()))); serverSocketChannel.configureBlocking(false); this.executorServiceMap = (Hashtable) mbeanServer.getAttribute(new ObjectName(warDeployerName), "ExecutorServiceMap"); this.urlClassLoaderMap = (Hashtable) mbeanServer.getAttribute(new ObjectName(warDeployerName), "UrlClassLoaderMap"); this.deployDirectory = serverConfig.getDeploydirectory(); //log.info("Nodesport=" + nodesport); this.nodesport = serverConfig.getNodesport().split(","); } catch (Exception e) { log.error("Error in creating server socket channel " + serverConfig.getServicesport(), e); // TODO Auto-generated catch block //e.printStackTrace(); } log.info("initialized"); }
From source file:org.apache.hadoop.hdfs.net.TcpPeerServer.java
/** * Create a non-secure TcpPeerServer./*from w w w .j a v a2 s . c o m*/ * * @param socketWriteTimeout The Socket write timeout in ms. * @param bindAddr The address to bind to. * @throws IOException */ public TcpPeerServer(int socketWriteTimeout, InetSocketAddress bindAddr) throws IOException { this.serverSocket = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket(); Server.bind(serverSocket, bindAddr, 0); }
From source file:ca.wumbo.doommanager.server.ServerManager.java
/** * Starts up the channels and selectors for net connections. This must be * called before executing the run() method. This is synchronized, though * multiple threads should not be calling initialize on this anyways. * //from w w w . j a v a 2s .c o m * @throws IOException * If any errors occur while setting up the connection handling. * * @throws IllegalArgumentException * If the IP is empty upon extraction from the socket channel. * * @throws RuntimeException * If there are multiple attempts to initialize the server. */ public void initialize() throws IOException { if (isInitialized) throw new RuntimeException("Attempting to initialize a server when it already has been."); log.trace("Initializing Server Manager."); listenPort = config.getServerConfig().getPort(); selector = Selector.open(); // Attempt to open a channel. log.debug("Attempting to bind server to port {}.", listenPort); serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(listenPort)); log.info("Successfully bound server to port {}.", listenPort); isInitialized = true; }
From source file:com.packetsender.android.PacketListenerService.java
@Override protected void onHandleIntent(Intent intent) { dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0), getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)); listenportTCP = dataStore.getTCPPort(); listenportUDP = dataStore.getUDPPort(); Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP)); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); startNotification();//from ww w . ja va 2s. c o m CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer response = null; try { response = encoder.encode(CharBuffer.wrap("response")); } catch (CharacterCodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { SocketAddress localportTCP = new InetSocketAddress(listenportTCP); SocketAddress localportUDP = new InetSocketAddress(listenportUDP); tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localportTCP); udpserver = DatagramChannel.open(); udpserver.socket().bind(localportUDP); tcpserver.configureBlocking(false); udpserver.configureBlocking(false); Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); receiveBuffer.clear(); shutdownListener = new Runnable() { public void run() { if (false) { try { tcpserver.close(); } catch (IOException e) { } try { udpserver.close(); } catch (IOException e) { } stopSelf(); } else { mHandler.postDelayed(shutdownListener, 2000); } } }; sendListener = new Runnable() { public void run() { //Packet fetchedPacket = mDbHelper.needSendPacket(); Packet[] fetchedPackets = dataStore.fetchAllServicePackets(); if (fetchedPackets.length > 0) { dataStore.clearServicePackets(); Log.d("service", DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets")); for (int i = 0; i < fetchedPackets.length; i++) { Packet fetchedPacket = fetchedPackets[i]; Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString())); } new SendPacketsTask().execute(fetchedPackets); } mHandler.postDelayed(sendListener, 2000); } }; //start shutdown listener mHandler.postDelayed(shutdownListener, 2000); //start send listener mHandler.postDelayed(sendListener, 5000); while (true) { try { // Handle per-connection problems below // Wait for a client to connect Log.d("service", DataStorage.FILE_LINE("waiting for connection")); selector.select(); Log.d("service", DataStorage.FILE_LINE("client connection")); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); Channel c = (Channel) key.channel(); if (key.isAcceptable() && c == tcpserver) { SocketChannel client = tcpserver.accept(); if (client != null) { Socket tcpSocket = client.socket(); packetCounter++; DataInputStream in = new DataInputStream(tcpSocket.getInputStream()); byte[] buffer = new byte[1024]; int received = in.read(buffer); byte[] bufferConvert = new byte[received]; System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = tcpSocket.getPort(); storepacket.port = tcpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP); Log.i("service", DataStorage.FILE_LINE("Got TCP")); //dataStore.SavePacket(storepacket); /* Intent tcpIntent = new Intent(); tcpIntent.setAction(ResponseReceiver.ACTION_RESP); tcpIntent.addCategory(Intent.CATEGORY_DEFAULT); tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name); sendBroadcast(tcpIntent); */ storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = "You"; storepacket.toIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.fromPort = tcpSocket.getLocalPort(); storepacket.port = tcpSocket.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); client.write(response); // send response } client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { DatagramSocket udpSocket; DatagramPacket udpPacket; byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer udpPacket = new DatagramPacket(buffer, buffer.length); udpSocket = udpserver.socket(); receiveBuffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer); if (clientAddress != null) { String fromAddress = clientAddress.getAddress().getHostAddress(); packetCounter++; int received = receiveBuffer.position(); byte[] bufferConvert = new byte[received]; System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = clientAddress.getAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = clientAddress.getPort(); storepacket.port = udpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP); //dataStore.SavePacket(storepacket); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = "You"; storepacket.toIP = clientAddress.getAddress().getHostAddress(); storepacket.fromPort = udpSocket.getLocalPort(); storepacket.port = clientAddress.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); //dataStore.SavePacket(storepacket); udpserver.send(response, clientAddress); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); } } } } } catch (java.io.IOException e) { Log.i("service", DataStorage.FILE_LINE("IOException ")); } catch (Exception e) { Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e))); } } } catch (BindException e) { //mDbHelper.putServiceError("Error binding to port"); dataStore.putToast("Port already in use."); Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e))); } catch (Exception e) { //mDbHelper.putServiceError("Fatal Error starting service"); Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e))); } stopNotification(); }
From source file:middleware.NewServerSocket.java
NewServerSocket(SharedData s) { sharedData = s;// www. j ava 2 s . c o m try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(s.getMiddlePortNum())); serverSocketChannel.configureBlocking(false); } catch (IOException e) { System.out.println("Error: cannot bind to port " + s.getMiddlePortNum()); e.printStackTrace(); } try { adminServerSocketChannel = ServerSocketChannel.open(); adminServerSocketChannel.socket().bind(new InetSocketAddress(s.getAdminPortNum())); adminServerSocketChannel.configureBlocking(false); } catch (IOException e) { System.out.println("Error: cannot bind to port " + s.getAdminPortNum()); e.printStackTrace(); } try { selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); adminServerSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { e.printStackTrace(); } keyIterator = null; dir = new File(sharedData.getFilePathName() + File.separator + "Transactions"); if (!dir.exists()) { dir.mkdirs(); } else { for (File f : dir.listFiles()) { if (!f.delete()) { // TODO } } } numWorkers = sharedData.getNumWorkers(); workers = new NewWorker[numWorkers]; for (int i = 0; i < numWorkers; ++i) { Selector tmpS = null; try { tmpS = Selector.open(); } catch (IOException e) { e.printStackTrace(); } workers[i] = new NewWorker(sharedData, tmpS); workers[i].start(); } data = new byte[sharedData.getMaxSize()]; buffer = ByteBuffer.wrap(data); endingMonitoring = false; sendingFiles = false; monitoring = false; dstatDeployed = false; failDeployDstat = false; configSetenv = false; mysql_user = null; mysql_pass = null; mysql_host = null; mysql_port = null; sharedData.allTransactionData = new ArrayList<TransactionData>(); sharedData.allTransactions = new ConcurrentSkipListMap<Integer, byte[]>(); // sharedData.allStatementsInfo = new ConcurrentLinkedQueue<byte[]>(); sharedData.allQueries = new ConcurrentSkipListMap<Long, QueryData>(); userInfo = Encrypt.getUsrMap(sharedData.getUserInfoFilePath()); fileBuffer = new byte[1024]; curUser = null; userList = new ArrayList<MiddleSocketChannel>(); dstat = null; ntpdate = null; stopRemoteDstat = null; incrementalLogQueue = new ArrayBlockingQueue<IncrementalLog>(64 * 1024); }
From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java
/** * Create and start a new listening service for out torrent, reporting * with our peer ID on the given address. * * <p>/*from w w w .j a va2s. c o m*/ * This binds to the first available port in the client port range * PORT_RANGE_START to PORT_RANGE_END. * </p> * * @param torrent The torrent shared by this client. * @param id This client's peer ID. * @param address The address to bind to. * @throws IOException When the service can't be started because no port in * the defined range is available or usable. */ ConnectionHandler(SharedTorrent torrent, String id, InetAddress address) throws IOException { this.torrent = torrent; this.id = id; // Bind to the first available port in the range // [PORT_RANGE_START; PORT_RANGE_END]. for (int port = ConnectionHandler.PORT_RANGE_START; port <= ConnectionHandler.PORT_RANGE_END; port++) { InetSocketAddress tryAddress = new InetSocketAddress(address, port); try { this.channel = ServerSocketChannel.open(); this.channel.socket().bind(tryAddress); this.channel.configureBlocking(false); this.address = tryAddress; break; } catch (IOException ioe) { // Ignore, try next port logger.warn("Could not bind to {}, trying next port...", tryAddress); } } if (this.channel == null || !this.channel.socket().isBound()) { throw new IOException("No available port for the BitTorrent client!"); } logger.info("Listening for incoming connections on {}.", this.address); this.listeners = new HashSet<IncomingConnectionListener>(); this.executor = null; this.thread = null; }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException { stopped = false;/*from w ww. ja v a2 s . c o m*/ executor = Executors.newFixedThreadPool(maxConnections); final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); if (maxBufferSize > 0) { serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize); final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < maxBufferSize) { logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port)); selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); }
From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java
public void listen() throws Exception { doListen = true;//from w ww.j a va 2s .com // allocate an unbound server socket channel ServerSocketChannel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below Selector selector = Selector.open(); // set the port the server channel will listen to serverSocket.bind(new InetSocketAddress(bind, port)); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (doListen) { // this may block for a long time, upon return the // selected set contains keys of the ready channels try { //System.out.println("Selecting with timeout="+timeout); int n = selector.select(timeout); //System.out.println("select returned="+n); if (n == 0) { continue; // nothing to do } // get an iterator over the set of selected keys Iterator it = selector.selectedKeys().iterator(); // look at each key in the selected set while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ, new ObjectReader(channel, selector, callback)); } // is there data to read on this channel? //System.out.println("key readable="+key.isReadable()); if (key.isReadable()) { readDataFromSocket(key); } else { //System.out.println("This shouldn't get called"); key.interestOps(key.interestOps() & (~key.OP_WRITE)); } // remove key from selected set, it's been handled it.remove(); } //System.out.println("Done with loop"); } catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); } catch (Exception x) { log.error("Unable to process request in ReplicationListener", x); } } //while serverChannel.close(); selector.close(); }
From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java
private void openClient() { try {/* w w w. jav a 2 s . com*/ this.socket = ServerSocketChannel.open(); this.port = this.discoverClientPort(); this.socket.configureBlocking(false); logger.info("Opened on port: {}", this.port); } catch (Exception e) { logger.error("Cannot connect because: {}", e.getMessage(), e); } }