Java源代码:服务器端口多线程监听类示例

package hjk.java;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.swing.JOptionPane;

public class ServerPortListener implements Runnable{
 /**
  * @keywords 自动化管理的 服务器端口多线程监听 工具类  
  * @status 可用  调试中
  * @future 下一步功能扩展: 连接数管理
  * @author Karl Jinkey  iamkarl@163.com 2010-05-20
  * @sample 使用样例: 
  *    ServerPortListener listener = new ServerPortListener(serverPort);
    Thread threadListener = new Thread(listener);
    threadListener.setDaemon(true); 
    threadListener.start();//启动一个监听器线程
    threadListener.join();//阻塞调用进程,等待客户端连接
    socket = listener.getSocket();//获得传入的连接
    if(socket==null){
     //TODO: 错误处理代码
    }else{
     //TODO: 进一步的Socket处理
    }
  */
 private static Integer objCount = 0;
 private static Map<Short, ServerSocket> serverMap = Collections.synchronizedMap(new HashMap<Short, ServerSocket>());
 private static Set<Socket> socketSet = Collections.synchronizedSet(new HashSet<Socket>());
 
 private ServerSocket server = null;
 private Socket socket = null;
 private short serverPort;
 public InfoMap lastError = new InfoMap();
 public ServerPortListener(short serverPort) {
  System.out.println(objCount);
  synchronized (objCount) {
   objCount++;
  }
  this.serverPort = serverPort;
 } 
 public Socket getSocket() {
  return socket;
 }

 public void setSocket(Socket socket) {
  this.socket = socket;
 }

 public short getServerPort() {
  return serverPort;
  
 }

 public void setServerPort(short serverPort) {
  this.serverPort = serverPort;
 }

 @Override
 public void run() {
  while(true){
   try {
    server = serverMap.get(serverPort);
    if(server!=null ){
     if(!server.isClosed()) break;//端口服务存在,跳出循环
     serverMap.remove(serverPort);
    }
    server = new ServerSocket(serverPort);
    serverMap.put(serverPort, server);
    server.setReuseAddress(true);
    break;
   } catch (IOException e) {
    //lastError.msg ="创建服务端口["+serverPort+"]时发生异常:"+e.toString();
    if(server!=null){
     try{
      server.close();
     }catch(IOException e2){
      lastError.msg ="关闭ServerSocket时发生异常:"+e2.toString();      
     }
    }
    int res = JOptionPane.showConfirmDialog(null,
      "创建服务端口["+serverPort+"]时发生异常:"+e.toString(), "错误提示:",JOptionPane.YES_NO_OPTION);
    if(res!=JOptionPane.YES_OPTION) {     
     return;
    }
    //System.gc();
    continue;
   }
   
  }
  
  while (true) {    
   try{
    //if(server.isBound()){//测试绑定状态:
     System.out.println("监听端口:"+serverPort);
     socket = server.accept();
     socketSet.add(socket);
     System.out.println("监听成功,启动服务,客户端IP:"+socket.getRemoteSocketAddress().toString());
     break;//监听到一个连接请求,跳出循环
//    }else{
//     server.close();
//     server = new ServerSocket(serverPort);
//     server.setReuseAddress(true);
//    }     
   }catch(Exception e){
    lastError.msg ="监听器异常终止:"+e.toString();
   }
  }
 }
 //释放资源:
 private void freeAll(){
  if(serverMap.size()!=0){
   Set<Short> set = serverMap.keySet();
   for(Short key:set){
    System.out.println("ser.close():"+objCount);
    ServerSocket ser = serverMap.get(key);
    if(ser!=null&&!ser.isClosed()){
     try{
      ser.close();
     }catch(IOException e){}
    }    
   }
  }
  if(socketSet.size()!=0){
   
   for(Socket so:socketSet){
    if(so!=null&&!so.isClosed()){
     try{
      so.close();
     }catch(IOException e){}
    }    
   }
  }  
 }
 @Override
 protected void finalize() throws Throwable {
  synchronized (objCount) {
   //System.out.println("objCount:"+objCount);
   objCount--;
   if(objCount==0){
    freeAll();
    super.finalize();
    return;
   }
  }
  if(socket!=null){
   if(!socket.isClosed()){
    try{
     socket.close();
    }catch(IOException e){}
   }
   socketSet.remove(socket);
  }
  super.finalize();
 }
}

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值