Netty 3.1 中文用户手册的问题

yangjunqing 发布于 2011/02/18 15:47
阅读 847
收藏 1

我看到1.9节时,讨论关闭一个服务端应用。大家有什么好的实现吗?

加载中
0
y
yangjunqing

我自己写了一种方式,参考的tomcat。大家还有别的方式吗?

package org.jboss.netty.example.securechat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.AccessControlException;
import java.util.Random;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Log4JLoggerFactory;

/**
 * Simple SSL chat server modified from TelnetServer.
 *
 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
 *
 * @version $Rev: 2080 $, $Date: 2010-01-26 18:04:19 +0900 (Tue, 26 Jan 2010) $
 */
public class SecureChatServer {
 /**
  * The shutdown command string we are looking for.
  */
 public static final String shutdown = "SHUTDOWN";
 static final ChannelGroup allChannels = new DefaultChannelGroup("加密聊天" );

 public static void main(String args[]) {
  if (args.length != 1) {
   System.err.println("Usage: " + SecureChatServer.class.getSimpleName() + " start/stop");
   return;
  }
  if (args[0].equals("start")) {
   startServer();
  } else if (args[0].equals("stop")) {
   stopServer();
  } else {
   System.err.println("Usage: " + SecureChatServer.class.getSimpleName() + " start/stop");
   return;
  }
 }
 public static void startServer(){
  InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());
  ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  ServerBootstrap bootstrap = new ServerBootstrap(factory);
  bootstrap.setPipelineFactory(new SecureChatServerPipelineFactory());
  // Bind and start to accept incoming connections.
  final Channel channel =bootstrap.bind(new InetSocketAddress(8080));
  allChannels.add(channel);
  System.out.println("加密聊天服务器在8080端口已经启动成功。");
  await();
  ChannelGroupFuture future = allChannels.close();  
  future.awaitUninterruptibly();  
  factory.releaseExternalResources();
 }
 public static void stopServer(){
        Socket socket;
  try {
   socket = new Socket("localhost", 9090);
   OutputStream stream = socket.getOutputStream();
         for (int i = 0; i < shutdown.length(); i++)
             stream.write(shutdown.charAt(i));
         stream.flush();
         stream.close();
         socket.close();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }
        System.out.println("已经向9090端口发出停止服务命令");
 }
 public static void await(){
  boolean stopAwait = false;
  /**
   * A random number generator that is only used if the shutdown command string is longer than 1024 characters.
   */
  Random random = null; 
  ServerSocket awaitSocket = null;
  try {
   awaitSocket = new ServerSocket(9090, 1,InetAddress.getByName("localhost"));
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  // Loop waiting for a connection and a valid command
  while (!stopAwait) {
   ServerSocket serverSocket = awaitSocket;
   if (serverSocket == null) {
    break;
   }
   // Wait for the next connection
   Socket socket = null;
   StringBuilder command = new StringBuilder();
   try {
    InputStream stream;
    try {
     socket = serverSocket.accept();
     socket.setSoTimeout(10 * 1000);  // Ten seconds
     stream = socket.getInputStream();
    } catch (AccessControlException ace) {
     ace.printStackTrace();
     continue;
    } catch (IOException e) {
     if (stopAwait) {
      // Wait was aborted with socket.close()
      break;
     }
     e.printStackTrace();
     break;
    }

    // Read a set of characters from the socket
    int expected = 1024; // Cut off to avoid DoS attack
    while (expected < shutdown.length()) {
     if (random == null)
      random = new Random();
     expected += (random.nextInt() % 1024);
    }
    while (expected > 0) {
     int ch = -1;
     try {
      ch = stream.read();
     } catch (IOException e) {
      e.printStackTrace();
      ch = -1;
     }
     if (ch < 32)  // Control character or EOF terminates loop
     break;
     command.append((char) ch);
     expected--;
    }
   } finally {
    // Close the socket now that we are done with it
    try {
     if (socket != null) {
      socket.close();
     }
    } catch (IOException e) {
     // Ignore
    }
   }
   // Match against our command string
   boolean match = command.toString().equals(shutdown);
   if (match) {
    System.out.println("在9090端口收到一个验证通过的停止服务命令,开始关闭服务.");
    break;
   } else
    System.out.println("收到一个错误的命令:" + command.toString());
  }
 } 
}

返回顶部
顶部