欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解基于java的Socket聊天程序——服务端(附demo)

程序员文章站 2024-03-11 17:58:49
 写在前面: 昨天在博客记录自己抽空写的一个socket聊天程序的初始设计,那是这个程序的整体设计,为了完整性,今天把服务端的设计细化记录一下,首页贴出sock...

 写在前面:

昨天在博客记录自己抽空写的一个socket聊天程序的初始设计,那是这个程序的整体设计,为了完整性,今天把服务端的设计细化记录一下,首页贴出socket聊天程序的服务端大体设计图,如下图:

详解基于java的Socket聊天程序——服务端(附demo)

功能说明:

服务端主要有两个操作,一是阻塞接收客户端的socket并做响应处理,二是检测客户端的心跳,如果客户端一段时间内没有发送心跳则移除该客户端,由server创建serversocket,然后启动两个线程池去处理这两件事(newfixedthreadpool,newscheduledthreadpool),对应的处理类分别是socketdispatcher、socketschedule,其中socketdispatcher根据socket不同的请求分发给不同sockethandler去处理,而socketwrapper则是对socket加了一层外壳包装,用lastalivetime记录socket最新的交互时间,socketholder存储当前跟服务端交互的socket集合。

具体实现:

[server.java]

server是服务端的入口,由server的start()方法启动serversocket,然后阻塞接收客户端的请求,交由socketdispatcher去分发,socketdispatcher由newfixedthread类型的线程池启动,当连接数超过最大数据时将被队列处理,使用scheduleatfixedrate启动socketschedule定时循环去监听客户端的心跳包,这两个类型都实现了runnable接口,下面给出服务端的代码:

package yaolin.chat.server;

import java.io.ioexception;
import java.net.serversocket;
import java.util.date;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.timeunit;

import yaolin.chat.common.constantvalue;
import yaolin.chat.util.loggerutil;

/**
 * 服务器
 * @author yaolin
 */
public class server {

  private final serversocket server;
  private final executorservice pool;
  
  public server() throws ioexception {
    server = new serversocket(constantvalue.server_port);
    pool = executors.newfixedthreadpool(constantvalue.max_pool_size);
  }

  public void start() {
    try {
      scheduledexecutorservice schedule = executors.newscheduledthreadpool(1);
      // watch dog. exception??
      schedule.scheduleatfixedrate(new socketschedule(), 10, constantvalue.time_out, timeunit.seconds);

      while (true) {
        pool.execute(new socketdispatcher(server.accept()));
        loggerutil.info("accept a client at " + new date());
      }
    } catch (ioexception e) {
      pool.shutdown();
    }
  }
  
  
  public static void main(string[] args) {
    try {
      new server().start();
    } catch (ioexception e) {
      loggerutil.error("server start failed! -> " + e.getmessage(), e);
    }
  }
}

[socketdispatcher.java]

server只是服务端的入口,并指挥中心,socketdispatcher才是服务端的指挥中心,对客户端不同的消息类型请求进行分发,让不同的sockethandler去处理对应的消息请求,这里服务端和客户端的消息交互都是用json数据,所有消息类都继承basemessage,所以将接收到数据转换成basemessage类型,再判断其类型,(数据类型模块属于common模块),这里需要提一下的是当消息类型是文件类型的时候会睡眠配置执行的间隔时间,这样filehandler才能有时间对文件流进行读取和重新发送给指定的客户端,而不会立即进入下一次循环对消息类型的判断(可能这里设计有点问题,不过暂时先这样做),下面给出socketdispatcher的代码:

/**
 * socketdispatcher
 * 
 * @author yaolin
 */
public class socketdispatcher implements runnable {

  private final socket socket;

  public socketdispatcher(socket socket) {
    this.socket = socket;
  }

  @override
  public void run() {
    if (socket != null) {
      while (!socket.isclosed()) {
        try {
          inputstream is = socket.getinputstream();
          string line = null;
          stringbuffer sb = null;
          
          if (is.available() > 0) {
            
            bufferedreader bufr = new bufferedreader(new inputstreamreader(is));
            sb = new stringbuffer();
            while (is.available() > 0 && (line = bufr.readline()) != null) {
              sb.append(line);
            }
            loggerutil.trach("receive [" + sb.tostring() + "] at " + new date());
            
            basemessage message = json.parseobject(sb.tostring(), basemessage.class);
            
            switch (message.gettype()) {
            case messagetype.alive:
              handlerfactory.gethandler(messagetype.alive).handle(socket, sb.tostring());
              break;
            case messagetype.chat:
              handlerfactory.gethandler(messagetype.chat).handle(socket, sb.tostring());
              break;
            case messagetype.file:
              handlerfactory.gethandler(messagetype.file).handle(socket, sb.tostring());
              loggerutil.trach("sever:pause to receive file");
              thread.sleep(constantvalue.message_period);
              break;
            case messagetype.login:
              handlerfactory.gethandler(messagetype.login).handle(socket, sb.tostring());
              break;
            case messagetype.logout:
              break;
            case messagetype.register:
              handlerfactory.gethandler(messagetype.register).handle(socket, sb.tostring());
              break;
            }
          } else {
            thread.sleep(constantvalue.message_period);
          }
        } catch (exception e) { // catch all handler exception
          loggerutil.error("socketdispatcher error!" + e.getmessage(), e);
        }
      }
    }
  }
}

[socketschedule.java]

跟server有直接关系的另一个类(组件)是socketschedule,socketschedule主要负责检测客户端的最新一次跟服务端的交互时间是否超过系统配置允许最大的时间,如果超过了,则将该客户端socket从服务端移除,否则更新客户端的最新一次跟服务端的交互时间。下面是具体的实现:

/**
 * remove socket from socketholder if lastalivetime > time_out
 * @author yaolin
 *
 */
public class socketschedule implements runnable {

  @override
  public void run() {
    for (string key : socketholder.keyset()) {
      socketwrapper wrapper = socketholder.get(key);
      if (wrapper != null && wrapper.getlastalivetime() != null) {
        if (((new date().gettime() - wrapper.getlastalivetime().gettime()) / 1000) > constantvalue.time_out) {
          // remove socket if timeout
          socketholder.remove(key);
        }
      }
    }
  }
}

[socketholder.java、socketwrapper.java]

从上面的代码可以看出,socketschedule#run()只是简单的对时间进行一次判断,真正有意义的其实是socketholder和socketwrapper,socketwrapper则是对socket加了一层外壳包装,socketholder的存储了当前有效时间内所有跟服务端有交互的客户端,socketholder以客户端的唯一标识(这里使用用户名),作为key,客户端所在的socket作为value的键值对形式存储,其中socketholder#flushclientstatus()的处理逻辑是用于通知其他客户端当前客户端的上线/离线状态,下面给出这两个类的具体实现:

/**
 * wrap socket, socketschedule remove socket if lastalivetime > time_out
 * @author yaolin
 *
 */
public class socketwrapper {

  private socket socket;
  private date lastalivetime;
  
  // full constructor
  public socketwrapper(socket socket, date lastalivetime) {
    this.socket = socket;
    this.lastalivetime = lastalivetime;
  }
  public socket getsocket() {
    return socket;
  }
  public void setsocket(socket socket) {
    this.socket = socket;
  }
  public date getlastalivetime() {
    return lastalivetime;
  }
  public void setlastalivetime(date lastalivetime) {
    this.lastalivetime = lastalivetime;
  }
}

/**
 * socketholder
 * @author yaolin
 */
public class socketholder {

  private static concurrentmap<string, socketwrapper> listsocketwrap = new concurrenthashmap<string, socketwrapper>();
  
  public static set<string> keyset() {
    return listsocketwrap.keyset();
  }
  
  public static socketwrapper get(string key) {
    return listsocketwrap.get(key);
  }
  
  public static void put(string key, socketwrapper value) {
    listsocketwrap.put(key, value);
    flushclientstatus(key, true);
  }
  
  public static socketwrapper remove(string key) {
    flushclientstatus(key, false);
    return listsocketwrap.remove(key);
  }
  
  public static void clear() {
    listsocketwrap.clear();
  }
  
  /**
   * <pre>content:{username:"",flag:false}</pre>
   * @param flag true:put,false:remove;
   */
  private static void flushclientstatus(string key, boolean flag) {
    clientnotifydto dto = new clientnotifydto(flag, key);
    returnmessage rm = new returnmessage().setkey(key.notify).setsuccess(true).setcontent(dto);
    rm.setfrom(constantvalue.server_name);
    for (string tokey : listsocketwrap.keyset()) {
      if (!tokey.equals(key)) { // not send to self
        rm.setto(tokey);
        socketwrapper wrap = listsocketwrap.get(tokey);
        if (wrap != null) {
          sendhelper.send(wrap.getsocket(), rm);
        }
      }
    }
  }
}

[sockethandler.java、handlerfactory.java、otherhandlerimpl.java]

socketdispatcher让不同的sockethandler去处理对应的消息请求,sockethandler的设计其实就是一套简单的工厂组件吧(其中returnhandler暂时由sendhelper实现信息传送,暂时没有用到,已经@deprecated ,这里还是给出),完整类图如下:

详解基于java的Socket聊天程序——服务端(附demo)

下面给出这一块的代码,为了缩小篇幅,将所有handler实现的代码收起来。

/**
 * sockethandler
 * @author yaolin
 */
public interface sockethandler {
  /**
   * handle client socket
   */
  public object handle(socket client,object data);
}
/**
 * sockethandlerfactory
 * @author yaolin
 */
public class handlerfactory {

  // can not create instance
  private handlerfactory(){}

  public static sockethandler gethandler(int type) {
    switch (type) {
    case messagetype.alive: // usually use
      return new alivehandler();
    case messagetype.chat:
      return new chathandler();
    case messagetype.login:
      return new loginhandler();
//    case messagetype.return:
//      return new returnhandler();
    case messagetype.logout:
      return new logouthandler();
    case messagetype.register:
      return new registerhandler();
    case messagetype.file:
      return new filehandler();
    }
    return null; // nullpointexception
  }
}

/**
 * alivesockethandler
 * @author yaolin
 */
public class alivehandler implements sockethandler {

  /**
   * @return null
   */
  @override
  public object handle(socket client, object data) {
    if (data != null) {
      basemessage message = json.parseobject(data.tostring(), basemessage.class);
      if (stringutil.isnotempty(message.getfrom())) {
        socketwrapper wrapper = socketholder.get(message.getfrom());
        if (wrapper != null) {
          wrapper.setlastalivetime(new date()); // keep socket ...
          socketholder.put(message.getfrom(), wrapper);
        }
      }
    }
    return null;
  }

}

/**
 * chathandler
 * 
 * @author yaolin
 */
public class chathandler implements sockethandler {

  @override
  public object handle(socket client, object data) {
    if (data != null) {
      chatmessage message = json.parseobject(data.tostring(), chatmessage.class);

      if (stringutil.isnotempty(message.getfrom()) && stringutil.isnotempty(message.getto())) {
        // exist & send
        if (socketholder.keyset().contains(message.getfrom())) {
          string owner = message.getfrom();
          message.setowner(owner); // owner will be display
          if (constantvalue.to_all.equals(message.getto())) { // one-to-all
            // to_all tab will be select;
            message.setfrom(constantvalue.to_all);
            for (string key : socketholder.keyset()) {
              // also send to self
              socketwrapper wrapper = socketholder.get(key);
              if (wrapper != null) {
                sendhelper.send(wrapper.getsocket(), message);
              }
            }
          } else {// one-to-one
            socketwrapper wrapper = socketholder.get(message.getto());
            if (wrapper != null) {
              // owner = from
              sendhelper.send(wrapper.getsocket(), message);
              // also send to self
              // to tab will be select;
              message.setfrom(message.getto()).setto(owner);
              sendhelper.send(client, message);
            }
          }
        }
      }
    }
    return null;
  }
}

public class filehandler implements sockethandler {

  @override
  public object handle(socket client, object data) {
    if (client != null) {
      filemessage message = json.parseobject(data.tostring(), filemessage.class);
      if (stringutil.isnotempty(message.getfrom()) && stringutil.isnotempty(message.getto())) {
        // exist & send
        if (socketholder.keyset().contains(message.getfrom())) {
          if (!constantvalue.to_all.equals(message.getto())) { // one-to-all
            socketwrapper wrapper = socketholder.get(message.getto());
            if (wrapper != null) {
              sendhelper.send(wrapper.getsocket(), message);
              try {
                if (client != null && wrapper.getsocket() != null && message.getsize() > 0) {
                  inputstream is = client.getinputstream();
                  outputstream os = wrapper.getsocket().getoutputstream();
                  int total = 0;
                  while (!client.isclosed() && !wrapper.getsocket().isclosed()) {
                    if (is.available() > 0) {
                      byte[] buff = new byte[constantvalue.buff_size];
                      int len = -1;
                      while (is.available() > 0 && (len = is.read(buff)) != -1) {
                        os.write(buff, 0, len);
                        total += len;
                        loggerutil.debug("send buff [" + len + "]");
                      }
                      os.flush();
                      if (total >= message.getsize()) {
                        loggerutil.info("send buff [ok]");
                        break;
                      }
                    }
                  }
                  // after send file
                  // send successfully
                  returnmessage result = new returnmessage().setkey(key.tip)
                      .setsuccess(true)
                      .setcontent(i18n.info_file_send_successfully);
                  result.setfrom(message.getto()).setto(message.getfrom())
                      .setowner(constantvalue.server_name);
                  sendhelper.send(client, result);
                  // receive successfully
                  result.setcontent(i18n.info_file_receive_successfully)
                      .setfrom(message.getfrom())
                      .setto(message.getto());
                  sendhelper.send(wrapper.getsocket(), result);
                }
              } catch (exception e) {
                loggerutil.error("handle file failed !" + e.getmessage(), e);
              }
            }
          }
        }
      }
    }
    return null;
  }
}

/**
 * loginhandler
 * 
 * @author yaolin
 *
 */
public class loginhandler implements sockethandler {

  private usrservice usrservice = new usrservice();

  @override
  public object handle(socket client, object data) {
    returnmessage result = new returnmessage();
    result.setsuccess(false);
    if (data != null) {
      loginmessage message = json.parseobject(data.tostring(), loginmessage.class);
      if (stringutil.isnotempty(message.getusername()) && stringutil.isnotempty(message.getpassword())) {
        if (usrservice.login(message.getusername(), message.getpassword()) != null) {
          result.setsuccess(true);
        } else {
          result.setmessage(i18n.info_login_error_data);
        }
        result.setfrom(constantvalue.server_name).setto(message.getusername());
      } else {
        result.setmessage(i18n.info_login_empty_data);
      }
      // after login
      result.setkey(key.login);
      if (result.issuccess()) { // hold socket
        socketholder.put(result.getto(), new socketwrapper(client, new date()));
      }
      sendhelper.send(client, result);
      if (result.issuccess()) { // send list user
        clientlistuserdto dto = new clientlistuserdto();
        dto.setlistuser(socketholder.keyset());
        result.setcontent(dto).setkey(key.listuser);
        sendhelper.send(client, result);
      }
    }
    return null;
  }

}

public class logouthandler implements sockethandler {

  @override
  public object handle(socket client, object data) {
    if (data != null) {
      logoutmessage message = json.parseobject(data.tostring(), logoutmessage.class);
      if (message != null && stringutil.isnotempty(message.getfrom())) {
        socketwrapper wrapper = socketholder.get(message.getfrom());
        socket socket = wrapper.getsocket();
        if (socket != null) {
          try {
            socket.close();
            socket = null;
          } catch (exception ignore) {
          }
        }
        socketholder.remove(message.getfrom());
      }
    }
    return null;
  }

}

public class registerhandler implements sockethandler {

  private usrservice usrservice = new usrservice();
  
  @override
  public object handle(socket client, object data) {
    returnmessage result = new returnmessage();
    result.setsuccess(false).setfrom(constantvalue.server_name);
    if (data != null) {
      registermessage message = json.parseobject(data.tostring(), registermessage.class);
      if (stringutil.isnotempty(message.getusername()) && stringutil.isnotempty(message.getpassword())) {
        if (usrservice.register(message.getusername(), message.getpassword()) != null) {
          result.setsuccess(true).setcontent(i18n.info_register_ok);
        } else {
          result.setmessage(i18n.info_register_client_exist);
        }
      } else {
        result.setmessage(i18n.info_register_empty_data);
      }
       
      if (stringutil.isnotempty(message.getusername())) {
        result.setto(message.getusername());
      }
      // after register
      result.setkey(key.register);
      sendhelper.send(client, result);
    }
    return null;
  }

}

 

/**
 * use sendhelper to send returnmessage, 
 * @see yaolin.chat.server.socketdispatcher#run()
 * @author yaolin
 */
@deprecated 
public class returnhandler implements sockethandler {

  /**
   * @param data returnmessage
   */
  @override
  public object handle(socket client, object data) {
    if (data != null) {
      returnmessage message = (returnmessage) data;
      if(stringutil.isnotempty(message.getfrom()) && stringutil.isnotempty(message.getto())) {
        socketwrapper wrap = socketholder.get(message.getto());
        if (wrap != null) {
          sendhelper.send(wrap.getsocket(), message);
        }
      }
    }
    return null;
  }

}

 用户业务:

服务端除了socket之外,还有一点点具体的业务,那就是用户的注册、登陆等,这里简单的列出usr和usrservice这两个类,这些业务暂时没有怎么实现,我并不打算在这个程序中引入orm框架,所以自己写一套dbutil(待改善),在这里也一并贴出来。

详解基于java的Socket聊天程序——服务端(附demo)

这里只进行了简单的校验,没有持久化存储到db中,下面是usr和usrservice:

public class usr {

  private long id;
  private string username;
  private string password;
  public long getid() {
    return id;
  }
  public void setid(long id) {
    this.id = id;
  }
  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getpassword() {
    return password;
  }
  public void setpassword(string password) {
    this.password = password;
  }
}

/**
 * // todo
 * @see yaolin.chat.server.usr.repository.usrrepository
 * @author yaolin
 *
 */
public class usrservice {
  // todo db 
  private static map<string,usr> db = new hashmap<string,usr>();
  
  public usr register(string username, string password) {
    if (stringutil.isempty(username) || stringutil.isempty(password)) {
      return null;
    }
    if (db.containskey(username)) {
      return null; // exist;
    }
    usr usr = new usr();
    usr.setusername(username);
    usr.setpassword(md5util.getmd5code(password));
    db.put(username, usr);
    return usr;
  }
  
  public usr login(string username, string password) {
    if (stringutil.isempty(username) || stringutil.isempty(password)) {
      return null;
    }
    if (db.containskey(username)) {
      usr usr = db.get(username);
      if (md5util.getmd5code(password).equals(usr.getpassword())) {
        return usr;
      }
    }
    return null;
  }
}

 下面是dbutil工具:

 /**
 * dbutils // todo 有待调整&优化!!
 * @author yaolin
 */
public class dbutil {
  // make connection used repeatedly
  private static final list<connection> cache = new linkedlist<connection>();
  private static string url;
  private static string driver;
  private static string user;
  private static string password;
  private static boolean debug;

  static {
    inputstream is = dbutil.class.getresourceasstream("/db.properties");
    try {
      properties p = new properties();
      p.load(is);
      url = p.getproperty("url");
      driver = p.getproperty("driver");
      user = p.getproperty("user");
      password = p.getproperty("password");
      // just for debug
      try {
        debug = boolean.valueof(p.getproperty("debug"));
      } catch (exception ignore) {
        debug = false;
      }
    } catch (exception e) {
      throw new runtimeexception(e);
    } finally {
      if (is != null) {
        try {
          is.close();
          is = null;
        } catch (exception ignore) {
        }
      }
    }
  }

  public synchronized static connection getconnection() {
    if (cache.isempty()) {
      cache.add(makeconnection());
    }
    connection conn = null;
    int i = 0;
    try {
      do {
        conn = cache.remove(i);
      } while (conn != null && conn.isclosed() && i < cache.size());
    } catch (exception ignore) {
    }

    try {
      if (conn == null || conn.isclosed()) {
        cache.add(makeconnection());
        conn = cache.remove(0);
      }
      return conn;
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  public synchronized static void close(connection connection) {
    try {
      if (connection != null && !connection.isclosed()) {
        if (debug)
          debug("release connection!");
        cache.add(connection);
      }
    } catch (sqlexception ignore) {
    }
  }

  public static object query(string sql, resultsetmapper mapper, object... args) {
    if (debug)
      debug(sql);
    connection conn = getconnection();
    preparedstatement ps = null;
    resultset rs = null;
    object result = null;
    try {
      ps = conn.preparestatement(sql);
      int i = 1;
      for (object object : args) {
        ps.setobject(i++, object);
      }
      rs = ps.executequery();
      result = mapper.mapper(rs);
    } catch (exception e) {
      throw new runtimeexception(e);
    } finally {
      try {
        if (rs != null) {
          rs.close();
          rs = null;
        }
        if (ps != null) {
          ps.close();
          ps = null;
        }
      } catch (exception ignore) {
      }
    }
    close(conn);
    return result;
  }

  public static int modify(string sql, object... args) {
    if (debug)
      debug(sql);
    connection conn = getconnection();
    preparedstatement ps = null;
    int row = 0;
    try {
      ps = conn.preparestatement(sql);
      int i = 1;
      for (object object : args) {
        ps.setobject(i++, object);
      }
      row = ps.executeupdate();
    } catch (exception e) {
      throw new runtimeexception(e);
    } finally {
      try {
        if (ps != null) {
          ps.close();
          ps = null;
        }
      } catch (exception ignore) {
      }
    }
    close(conn);
    return row;
  }

  public static int[] batch(list<string> sqls) {
    if (debug)
      debug(sqls.tostring());
    connection conn = getconnection();
    statement stmt = null;
    int[] row;
    try {
      stmt = conn.createstatement();
      for (string sql : sqls) {
        stmt.addbatch(sql);
      }
      row = stmt.executebatch();
    } catch (exception e) {
      throw new runtimeexception(e);
    } finally {
      try {
        if (stmt != null) {
          stmt.close();
          stmt = null;
        }
      } catch (exception ignore) {
      }
    }
    close(conn);
    return row;
  }

  public static int[] batch(string sql, preparedstatementsetter setter) {
    if (debug)
      debug(sql);
    connection conn = getconnection();
    preparedstatement ps = null;
    int[] row;
    try {
      ps = conn.preparestatement(sql);
      setter.setter(ps);
      row = ps.executebatch();
    } catch (exception e) {
      throw new runtimeexception(e);
    } finally {
      try {
        if (ps != null) {
          ps.close();
          ps = null;
        }
      } catch (exception ignore) {
      }
    }
    close(conn);
    return row;
  }

  private static connection makeconnection() {
    try {
      class.forname(driver).newinstance();
      connection conn = drivermanager.getconnection(url, user, password);
      if (debug)
        debug("create connection!");
      return conn;
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  private static void debug(string sqls) {
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    system.out.println(sdf.format(new date()) 
        + " debug " + thread.currentthread().getid() 
        + " --- [" + thread.currentthread().getname() + "] " + "excute sqls : " + sqls);
  }
}

/**
 * preparedstatementsetter
 * @author yaolin
 */
public interface preparedstatementsetter {
  public void setter(preparedstatement ps);
}

/**
 * resultsetmapper
 * @author yaolin
 */
public interface resultsetmapper {
  public object mapper(resultset rs);
}

源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。