⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 quickserver.java

📁 一个用java编写的服务器,对于学习网络编程的人来说是个很好的例子
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
		//v1.3.3
		if(getSecurityManagerClass()!=null) {
			System.setSecurityManager(getSecurityManager());
		}
		
		blockingMode = getBasicConfig().getServerMode().getBlocking();

		setServiceState(Service.INIT);
		t = new Thread(this, "QuickServer - "+getName());
		t.start();

		do {
			Thread.yield();	
		} while(getServiceState()==Service.INIT);

		if(getServiceState()!=Service.RUNNING) {			
			if(exceptionInRun!=null)
				throw new AppException("Could not start server "+getName()
					+"! Details: "+exceptionInRun);
			else
				throw new AppException("Could not start server "+getName());
		}
		lastStartTime = new java.util.Date();
		logger.fine("Started "+getName()+", Date: "+lastStartTime);
	}

	/**
	 * Stops the QuickServer.
	 *
	 * @exception org.quickserver.net.AppException 
	 *  if could not stop server
	 * @since 1.1
	 * @see #stopService
	 */
	public void stopServer() throws AppException {
		processServerHooks(ServerHook.PRE_SHUTDOWN);
		logger.warning("Stopping "+getName());
		stopServer = true;
		Socket death = null;
		if(isClosed()==true) {
			logger.warning("Server "+getName()+" is not running!");
			throw new AppException("Server "+getName()+" is not running!");
		}
		try	{
			if(getBlockingMode()==true) {
				if(getSecure().isEnable()==false) {
					death = new Socket(server.getInetAddress(), 
						server.getLocalPort());
					death.getInputStream().read();
					death.close();
				} else {
					death = getSSLSocketFactory().createSocket(
						server.getInetAddress(), server.getLocalPort());
					Thread.currentThread().sleep(100);
					death.close();
				}
			}

			if(serverSocketChannel!=null) {
				serverSocketChannel.close();
			}

		} catch(IOException e){
			logger.fine("IOError stopping "+getName()+": "+e);
		} catch(Exception e){
			logger.warning("Error stopping "+getName()+": "+e);
			throw new AppException("Error in stopServer "+getName()+": "+e);
		}

		for(int i=0;getServiceState()!=Service.STOPPED;i++) {
			try {
				Thread.sleep(60);
			} catch(Exception e) {
				logger.warning("Error waiting for "+getName()+" to fully stop. Error: "+e);
			}
			if(i>1000) {
				logger.severe("Server was not stopped even after 10sec.. will terminate now.");
				System.exit(-1);
			}
		}
		if(adminServer==null || getQSAdminServer().getServer()!=this) {
			//so this is not qsadmin
			setClassLoader(null);
		}
		logger.info("Stopped "+getName());
	}

	/**
	 * Restarts the QuickServer.
	 *
	 * @exception org.quickserver.net.AppException 
	 *  if could not stop server or if it could not start the server.
	 * @since 1.2
	 */
	public void restartServer() throws AppException {
		stopServer();
		startServer();
	}

    /**
     * Returns the name of the QuickServer. Default is 'QuickServer'.
     * @see #setName
     */
	public String getName() {
		return serverName;
	}
    /**
     * Sets the name for the QuickServer
     * @param name for the QuickServer
     * @see #getName
     */
	public void setName(String name) {
		serverName = name;
		logger.finest("Set to : "+name);
	}

	/**
     * Returns the Server Banner of the QuickServer
     * @see #setServerBanner
     */
	public String getServerBanner() {
		return serverBanner;
	}
    /**
     * Sets the serverBanner for the QuickServer
	 * that will be displayed on the standard output [console]
	 * when server starts. <br>&nbsp;<br>
	 * To set welcome message to your client
	 * {@link ClientEventHandler#gotConnected}
     * @param banner for the QuickServer
     * @see #getServerBanner
     */
	public void setServerBanner(String banner) {
		serverBanner = banner;
		logger.finest("Set to : "+banner);
	}

    /**
     * Sets the port for the QuickServer to listen on.
	 * If not set, it will run on Port 9876 
	 * @param port to listen on.
     * @see #getPort
     */
	public void setPort(int port) {		
		if(port<0) {
			throw new IllegalArgumentException("Port number can not be less than 0!");
		}
		serverPort=port;
		logger.finest("Set to "+port);
	}
	/**
     * Returns the port for the QuickServer.
     * @see #setPort
     */
	public int getPort() {
		if(isClosed()==false) {
			return server.getLocalPort();
		}

		if(getSecure().isEnable()==false) {
			return serverPort;
		} else {
			int _port = getSecure().getPort();
			if(_port == -1) 
				return serverPort;
			else
				return _port;
		}
	}

	/**
     * Sets the ClientCommandHandler class that interacts with 
	 * client sockets.
	 * @param handler the fully qualified name of the class that 
	 *  implements {@link ClientCommandHandler}
	 * @see #getClientCommandHandler
     */
	public void setClientCommandHandler(String handler) {
		clientCommandHandlerString = handler;
		logger.finest("Set to "+handler);
	}	
	/**
     * Returns the ClientCommandHandler class that interacts with 
	 * client sockets.
	 * @see #setClientCommandHandler
	 * @since 1.1
     */
	public String getClientCommandHandler() {
		return clientCommandHandlerString;
	}

	/**
     * Sets the ClientAuthenticationHandler class that 
	 * handles the authentication of a client.
	 * @param authenticator the fully qualified name of the class 
	 * that implements {@link ClientAuthenticationHandler}.
	 * @see #getClientAuthenticationHandler
	 * @since 1.4.6
     */
	public void setClientAuthenticationHandler(String authenticator) {
		clientAuthenticationHandlerString = authenticator;
		logger.finest("Set to "+authenticator);
	}
	/**
     * Returns the ClientAuthenticationHandler class that 
	 * handles the authentication of a client.
	 * @see #setClientAuthenticationHandler
	 * @since 1.4.6
     */
	public String getClientAuthenticationHandler() {
		return clientAuthenticationHandlerString;
	}

	/**
     * Sets the Authenticator class that 
	 * handles the authentication of a client.
	 * @param authenticator the fully qualified name of the class 
	 * that implements {@link Authenticator} or {@link ClientAuthenticationHandler}.
	 * @see #getAuthenticator
	 * @deprecated since 1.4.6 use setClientAuthenticationHandler
	 * @since 1.3
     */
	public void setAuthenticator(String authenticator) {
		clientAuthenticationHandlerString = authenticator;
		logger.finest("Set to "+authenticator);
	}
	/**
     * Returns the Authenticator class that 
	 * handles the authentication of a client.
	 * @see #setAuthenticator
	 * @deprecated since 1.4.6 use getClientAuthenticationHandler
	 * @since 1.3
     */
	public String getAuthenticator() {
		return clientAuthenticationHandlerString;
	}

	/**
     * Sets the ClientData class that carries client data.
	 * @param data the fully qualified name of the class that 
	 * extends {@link ClientData}.
	 * @see #getClientData
     */
	public void setClientData(String data) {
		this.clientDataString = data;
		logger.finest("Set to "+data);
	}
	/**
     * Returns the ClientData class string that carries client data  
	 * @return the fully qualified name of the class that 
	 * implements {@link ClientData}.
	 * @see #setClientData
     */
	public String getClientData() {
		return clientDataString;
	}

	/**
     * Sets the client socket's timeout.
	 * @param time client socket timeout in milliseconds.
	 * @see #getTimeout
     */
	public void setTimeout(int time) {
		if(time>0)
			socketTimeout = time;
		else
			socketTimeout = 0;
		logger.finest("Set to "+socketTimeout);
	}	
	/**
     * Returns the Client socket timeout in milliseconds.
	 * @see #setTimeout
     */
	public int getTimeout() {
		return socketTimeout;
	}

	/** 
	 * Sets max allowed login attempts.
	 * @since 1.2
	 * @see #getMaxAuthTry
	 */
	public void setMaxAuthTry(int authTry) {
		maxAuthTry = authTry;
		logger.finest("Set to "+authTry);
	}
	/** 
	 * Returns max allowed login attempts. Default is <code>5</code>.
	 * @since 1.2
	 * @see #setMaxAuthTry
	 */
	public int getMaxAuthTry() {
		return maxAuthTry;
	}

	/** 
	 * Sets message to be displayed when maximum allowed login 
	 * attempts has reached.
	 * Default is : -ERR Max Auth Try Reached
	 * @see #getMaxAuthTryMsg
	 */
	public void setMaxAuthTryMsg(String msg) {
		maxAuthTryMsg = msg;
		logger.finest("Set to "+msg);
	}
	/** 
	 * Returns message to be displayed when maximum allowed login 
	 * attempts has reached.
	 * @see #getMaxAuthTryMsg
	 */
	public String getMaxAuthTryMsg() {
		return maxAuthTryMsg;
	}

	/**
	 * Sets timeout message. 
	 * Default is : -ERR Timeout
	 * @see #getTimeoutMsg
	 */
	public void setTimeoutMsg(String msg) {
		timeoutMsg = msg;
		logger.finest("Set to "+msg);
	}
	/** 
	 * Returns timeout message.
	 * @see #setTimeoutMsg
	 */
	public String getTimeoutMsg() {
		return timeoutMsg;
	}

	private TheClient initTheClient() {
		TheClient theClient = new TheClient();
		theClient.setServer(QuickServer.this);
		theClient.setTimeoutMsg(getTimeoutMsg());
		theClient.setMaxAuthTry(getMaxAuthTry()); //v1.2
		theClient.setMaxAuthTryMsg(getMaxAuthTryMsg());
		
		theClient.setClientEventHandler(clientEventHandler);
		theClient.setClientExtendedEventHandler(clientExtendedEventHandler); //v1.4.6
		theClient.setClientCommandHandler(clientCommandHandler);
		theClient.setClientObjectHandler(clientObjectHandler); //v1.2
		theClient.setClientBinaryHandler(clientBinaryHandler); //v1.4
		theClient.setClientWriteHandler(clientWriteHandler); //v1.4.5
		theClient.setAuthenticator(authenticator); //v1.3
		theClient.setClientAuthenticationHandler(clientAuthenticationHandler); //v1.4.6
		theClient.setTimeout(socketTimeout);
		theClient.setMaxConnectionMsg(maxConnectionMsg);
		theClient.setCommunicationLogging(getCommunicationLogging()); //v1.3.2
		return theClient;
	}

	public void run() {
		exceptionInRun = null;
		TheClient theClient = initTheClient();
		try {
			stopServer = false;

			closeAllPools();
			initAllPools();
			
			makeServerSocket();
			System.out.println(serverBanner); //print banner
			setServiceState(Service.RUNNING); //v1.2
			
			processServerHooks(ServerHook.POST_STARTUP); //v1.3.3
			if(getBlockingMode()==false) {
				runNonBlocking(theClient);
				if(stopServer==true) {
					logger.finest("Closing selector for "+getName());
					selector.close();
				}
				return;
			} else {
				runBlocking(theClient);
			}
		} catch(BindException e) {
			exceptionInRun = e;
			logger.severe(getName()+" BindException for Port "+getPort()+" @ "+
				getBindAddr().getHostAddress()+" : "+e.getMessage());
		} catch(javax.net.ssl.SSLException e) {
			exceptionInRun = e;
			logger.severe("SSLException "+e);
			logger.fine("StackTrace:\n"+MyString.getStackTrace(e));
		} catch(IOException e) {
			exceptionInRun = e;
			logger.severe("IOError "+e);
			logger.fine("StackTrace:\n"+MyString.getStackTrace(e));
		} catch(Exception e) {
			exceptionInRun = e;
			logger.severe("Error "+e);
			logger.fine("StackTrace:\n"+MyString.getStackTrace(e));
		} finally {
			if(getBlockingMode()==true) {
				logger.warning("Closing "+getName());
				try	{
					if(isClosed()==false) {						
						server.close();
					}
				} catch(Exception e){
					throw new RuntimeException(e);
				}
				server = null;
				serverSocketChannel = null;

				setServiceState(Service.STOPPED);
				logger.warning("Closed "+getName());

				processServerHooks(ServerHook.POST_SHUTDOWN);
			} else if(getBlockingMode()==false && exceptionInRun!=null) {
				logger.warning("Closing "+getName()+" - Had Error: "+exceptionInRun);
				try	{
					if(isClosed()==false) {
						if(serverSocketChannel!=null)
							serverSocketChannel.close();
						if(server!=null)
							server.close();
					}
				} catch(Exception e){
					throw new RuntimeException(e);
				}		

				server = null;
				serverSocketChannel = null;

				setServiceState(Service.STOPPED);
				logger.warning("Closed "+getName());

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -