下面列出了java.net.ServerSocket#bind ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
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);
}
}
@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);
}
}
/**
* 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;
}
@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);
}
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;
}
}
@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);
}
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();
}
private ServerSocket bindSocket(ServerSocket socket) throws IOException {
if (reuseAddress) {
socket.setReuseAddress(true);
}
socket.bind(new InetSocketAddress(getPort()), 2 * getMaxActiveClientCount());
return socket;
}
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;
}
/**
* 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;
}
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;
}
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());
}
@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();
}
@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;
}
Server(boolean expectAuthToSucceed) throws IOException {
super("TestTransparentNTLM-Server");
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(LOOPBACK, 0));
this.expectAuthToSucceed = expectAuthToSucceed;
}
/**
* 启动服务器。
*
* @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);
}
}
/** {@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() + ']');
}
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()));
}
}
/**
* 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);
}