Java Code Examples for java.net.ServerSocket#bind()

The following examples show how to use java.net.ServerSocket#bind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Receiver.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Starts up the server. The server that has started accepts and handles TCP requests.
 *
 * @throws IOException if I/O error occurred at startup
 */
public void startup() throws IOException {

   // Create endpoint and inform about starting
   LOG.info("Starting TCP server bound to " + StringUtils.toString(endpoint));

   // Check preconditions
   verifyStartable();

   // Bind sockets
   for (final SelectionKey selectionKey : selector.keys()) {

      // Bind server socket
      try {
         final ServerSocket serverSocket = ((ServerSocketChannel) selectionKey.channel()).socket();
         serverSocket.setReceiveBufferSize(SystemProperty.BUFFER_SIZE);
         serverSocket.setReuseAddress(true);
         serverSocket.bind(endpoint);
      } catch (final BindException e) {
         throw createDetailedBindException(e, endpoint);
      }
   }

   // Start selector thread
   selectorThread.start();
}
 
Example 2
Source File: MockServer.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
public MockServer() {

		try {
			ssc = ServerSocketChannel.open();
			ssc.configureBlocking(false);

			ServerSocket serverSocket = ssc.socket();
			serverSocket.bind(new InetSocketAddress(0));
			port = serverSocket.getLocalPort();

			selector = Selector.open();

			ssc.register(selector, SelectionKey.OP_ACCEPT);
		} catch (Exception e) {
			throw new RuntimeException("crap", e);
		}
	}
 
Example 3
Source File: MultiThreadEchoServer.java    From new-bull with MIT License 5 votes vote down vote up
@Override
public void start(int port) throws IOException {
    serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress("0.0.0.0", port));

    serverThread = new ServerThread();
    serverThread.start();
}
 
Example 4
Source File: EventBusServer.java    From ipc-eventbus with Apache License 2.0 5 votes vote down vote up
@Override
public EventBusServer build() throws EventBusException {
  try {
    ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket();
    serverSocket.bind(new InetSocketAddress(address, port));
    return new DefaultEventBusServer(busId != null ? busId : (serverSocket.getInetAddress().getHostAddress() + ":" + serverSocket.getLocalPort()), serverSocket, errorListener);
  } catch (IOException e) {
    throw new EventBusIOException("Cannot bind on " + address + ":" + port + " : " + e.getMessage(), e);
  }
}
 
Example 5
Source File: EchoServer.java    From portforward with Apache License 2.0 5 votes vote down vote up
public EchoServer(InetSocketAddress from) throws IOException {
    this.from = from;
    serverSocket = new ServerSocket();
    serverSocket.setReuseAddress(true);
    serverSocket.bind(from);
    String hostname = from.getHostName();
    if (hostname == null) hostname = "*";
    log.info("Ready to accept client connection on " + hostname + ":" + from.getPort());
}
 
Example 6
Source File: TestHelper.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a unused random port.
 */
public static int getRandomPort()
    throws IOException {
  ServerSocket sock = new ServerSocket();
  sock.bind(null);
  int port = sock.getLocalPort();
  sock.close();

  return port;
}
 
Example 7
Source File: PortRange.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
private ServerSocket createServerSocket(int port, ServerSocketFactory ssf, String bindIP) throws IOException {
    ServerSocket ss = ssf.createServerSocket();
    if (_bufferSize > 0) {
        ss.setReceiveBufferSize(_bufferSize);
    }
    if (bindIP == null) {
        ss.bind(new InetSocketAddress(port), 1);
    } else {
        ss.bind(new InetSocketAddress(bindIP, port), 1);
    }
    return ss;
}
 
Example 8
Source File: JcloudsLocationUsageTrackingTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun = true)
@Override
public void setUp() throws Exception {
    super.setUp();
    RecordingSshTool.clear();

    app = managementContext.getEntityManager().createEntity(EntitySpec.create(TestApplication.class)
            .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
    entity = app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
    
    serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(Networking.getReachableLocalHost(), 0), 0);
}
 
Example 9
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void bind(InetSocketAddress addr, int backlog) throws IOException {
   if (this.bound) {
      throw new BindException("HttpServer already bound");
   } else if (addr == null) {
      throw new NullPointerException("null address");
   } else {
      ServerSocket socket = this.schan.socket();
      socket.bind(addr, backlog);
      this.bound = true;
   }
}
 
Example 10
Source File: NioTcpAcceptor.java    From craft-atom with MIT License 5 votes vote down vote up
@Override
protected void bindByProtocol(SocketAddress address) throws IOException {
	ServerSocketChannel ssc = ServerSocketChannel.open();
	ssc.configureBlocking(false);
	ServerSocket ss = ssc.socket();
	ss.setReuseAddress(config.isReuseAddress());
	ss.bind(address, config.getBacklog());
	ssc.register(selector, SelectionKey.OP_ACCEPT);
	boundmap.put(address, ssc);
}
 
Example 11
Source File: SocketServer.java    From ipc-eventbus with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

    ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket();
    serverSocket.bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(args[0])));
    Socket socket = serverSocket.accept();
    System.out.println("server read from client: " + new ObjectInputStream(socket.getInputStream()).readObject());
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
    objectOutputStream.writeObject("hello world!");
    objectOutputStream.flush();
    socket.close();
    serverSocket.close();
  }
 
Example 12
Source File: TlsHtmlAdaptorServer.java    From cougar with Apache License 2.0 5 votes vote down vote up
private ServerSocket bindSocket(ServerSocket socket) throws IOException {
    if (reuseAddress) {
        socket.setReuseAddress(true);
    }
    socket.bind(new InetSocketAddress(getPort()), 2 * getMaxActiveClientCount());
    return socket;
}
 
Example 13
Source File: RmidViaInheritedChannel.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public synchronized Channel inheritedChannel() throws IOException {
    System.err.println("RmidSelectorProvider.inheritedChannel");
    if (channel == null) {
        /*
         * Create server socket channel and bind server socket.
         */
        channel = ServerSocketChannel.open();
        ServerSocket serverSocket = channel.socket();
        serverSocket.bind(
             new InetSocketAddress(InetAddress.getLocalHost(),
             TestLibrary.RMIDVIAINHERITEDCHANNEL_ACTIVATION_PORT));
        System.err.println("serverSocket = " + serverSocket);

        /*
         * Notify test that inherited channel was created.
         */
        try {
            System.err.println("notify test...");
            Registry registry =
                LocateRegistry.getRegistry(TestLibrary.RMIDVIAINHERITEDCHANNEL_REGISTRY_PORT);
            Callback obj = (Callback) registry.lookup("Callback");
            obj.notifyTest();
        } catch (NotBoundException nbe) {
            throw (IOException)
                new IOException("callback object not bound").
                    initCause(nbe);
        }
    }
    return channel;
}
 
Example 14
Source File: RestrictingRMISocketFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ServerSocket} which is bound to an specific address and
 * the given port. The address can be specified by the System Property
 * james.jmx.address. If none is given it will use localhost
 */
@Override
public ServerSocket createServerSocket(int port) throws IOException {
    ServerSocket socket = new ServerSocket();
    socket.bind(new InetSocketAddress(address, port));
    sockets.add(socket);
    return socket;
}
 
Example 15
Source File: IpcSharedMemoryServerEndpoint.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
    IpcSharedMemoryNativeLoader.load(log);

    pid = IpcSharedMemoryUtils.pid();

    if (pid == -1)
        throw new IpcEndpointBindException("Failed to get PID of the current process.");

    if (size <= 0)
        throw new IpcEndpointBindException("Space size should be positive: " + size);

    String tokDirPath = this.tokDirPath;

    if (F.isEmpty(tokDirPath))
        throw new IpcEndpointBindException("Token directory path is empty.");

    tokDirPath = tokDirPath + '/' + locNodeId.toString() + '-' + IpcSharedMemoryUtils.pid();

    tokDir = U.resolveWorkDirectory(workDir, tokDirPath, false);

    if (port <= 0 || port >= 0xffff)
        throw new IpcEndpointBindException("Port value is illegal: " + port);

    try {
        srvSock = new ServerSocket();

        // Always bind to loopback.
        srvSock.bind(new InetSocketAddress("127.0.0.1", port));
    }
    catch (IOException e) {
        // Although empty socket constructor never throws exception, close it just in case.
        U.closeQuiet(srvSock);

        throw new IpcEndpointBindException("Failed to bind shared memory IPC endpoint (is port already " +
            "in use?): " + port, e);
    }

    gcWorker = new GcWorker(igniteInstanceName, "ipc-shmem-gc", log);

    new IgniteThread(gcWorker).start();

    if (log.isInfoEnabled())
        log.info("IPC shared memory server endpoint started [port=" + port +
            ", tokDir=" + tokDir.getAbsolutePath() + ']');
}
 
Example 16
Source File: AEProxyImpl.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
public
AEProxyImpl(
	int				_port,
	long			_connect_timeout,
	long			_read_timeout,
	AEProxyHandler	_proxy_handler )
	throws AEProxyException
{
	port					= _port;
	connect_timeout			= _connect_timeout;
	read_timeout			= _read_timeout;
	proxy_handler			= _proxy_handler;

	String	name = "Proxy:" + port;

	read_selector	 = new VirtualChannelSelector( name, VirtualChannelSelector.OP_READ, false );
	connect_selector = new VirtualChannelSelector( name, VirtualChannelSelector.OP_CONNECT, true );
	write_selector	 = new VirtualChannelSelector( name, VirtualChannelSelector.OP_WRITE, true );

	try{

		ssc = ServerSocketChannel.open();

		ServerSocket ss	= ssc.socket();

		ss.setReuseAddress(true);

		ss.bind(  new InetSocketAddress( InetAddress.getByName("127.0.0.1"), port), 128 );

		if ( port == 0 ){

			port	= ss.getLocalPort();
		}

		new AEThread2("AEProxy:connect.loop")
		{
			@Override
			public void
			run()
			{
				selectLoop( connect_selector );
			}
		}.start();


		new AEThread2("AEProxy:read.loop")
		{
			@Override
			public void
			run()
			{
				selectLoop( read_selector );
			}
		}.start();

		new AEThread2("AEProxy:write.loop")
		{
			@Override
			public void
			run()
			{
				selectLoop( write_selector );
			}
		}.start();


		new AEThread2("AEProxy:accept.loop")
		{
			@Override
			public void
			run()
			{
				acceptLoop( ssc );
			}
		}.start();

		if (Logger.isEnabled())
			Logger.log(new LogEvent(LOGID, "AEProxy: listener established on port "
					+ port));

	}catch( Throwable e){

		Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
				LogAlert.AT_ERROR, "Tracker.alert.listenfail"), new String[] { ""
				+ port + " (proxy)" });

		if (Logger.isEnabled())
			Logger.log(new LogEvent(LOGID, "AEProxy: listener failed on port "
					+ port, e));

		throw( new AEProxyException( "AEProxy: accept fails: " + e.toString()));
	}
}
 
Example 17
Source File: NioEchoServer.java    From JavaTutorial with Apache License 2.0 4 votes vote down vote up
/**
 * 启动服务器。
 * 
 * @param port 服务监听的端口
 * @param selectTimeout {@link Selector}检查通道就绪状态的超时时间(单位:毫秒)
 */
private static void startServer(int port, int selectTimeout) {
    ServerSocketChannel serverChannel = null;
    try {
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress(port));
        if (logger.isLoggable(Level.INFO)) {
            logger.info("NIO echo网络服务启动完毕,监听端口:" +port);
        }
        
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        while (true) {
            int selectNum = selector.select(selectTimeout);
            if (0 == selectNum) {
                continue;
            }
            
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) it.next();
                
                // 接受新的Socket连接
                if (selectionKey.isAcceptable()) {
                    acceptNew(selector, selectionKey);
                }
                
                // 读取并处理Socket的数据
                if (selectionKey.isReadable()) {
                    readData(selector, selectionKey);
                }
                
                it.remove();
            } // end of while iterator
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "处理网络连接出错", e);
    }
}
 
Example 18
Source File: TestTransparentNTLM.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
Server(boolean expectAuthToSucceed) throws IOException {
    super("TestTransparentNTLM-Server");
    serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(LOOPBACK, 0));
    this.expectAuthToSucceed = expectAuthToSucceed;
}
 
Example 19
Source File: SocketBindingManagerImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public ServerSocket createServerSocket(String name, int port, int backlog) throws IOException {
    final ServerSocket serverSocket = createServerSocket(name);
    serverSocket.bind(new InetSocketAddress(port), backlog);
    return serverSocket;
}
 
Example 20
Source File: HttpServer.java    From embedhttp with MIT License 2 votes vote down vote up
/**
 * Bind the server to the specified SocketAddress
 *
 * @param addr The address to bind to
 * @throws IOException If an error occurs while binding, usually port already in
 * use.
 */
public void bind(SocketAddress addr) throws IOException {
	socket = new ServerSocket();
	socket.bind(addr);
}