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

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

程序员文章站 2024-03-09 09:29:47
写在前面: 上周末抽点时间把自己写的一个简单socket聊天程序的和细化设计记录了一下,周二终于等来毕业前考的软考证书,然后接下来就是在加班的日子度过了,今天正好周五...

写在前面:

上周末抽点时间把自己写的一个简单socket聊天程序的和细化设计记录了一下,周二终于等来毕业前考的软考证书,然后接下来就是在加班的日子度过了,今天正好周五,打算把客户端的详细设计和common模块记录一下,因为这个周末开始就要去忙其他东西了。

设计:

客户端设计主要分成两个部分,分别是socket通讯模块设计和ui相关设计。

客户端socket通讯设计:

这里的设计其实跟服务端的设计差不多,不同的是服务端是接收心跳包,而客户端是发送心跳包,由于客户端只与一个服务端进行通讯(客户端之间的通讯也是由服务端进行分发的),所以这里只使用了一个大小为2的线程池去处理这两件事(newfixedthreadpool(2)),对应的处理类分别是receivelistener、keepalivedog,其中receivelistener在初始化的时候传入一个callback作为客户端收到服务端的消息的回调,callback的默认实现是defaultcallback,defaultcallback根据不同的事件通过hf分发给不同handler去处理,而clientholder则是存储当前客户端信息,设计如下:

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

socket通讯模块具体实现:

[client.java]

client是客户端连接服务端的入口,创建client需要指定一个callback作为客户端接收服务端消息时的回调,然后由client的start()方法启动对服务端的监听(receivelistener),当receivelistener接收到服务端发来的数据时,调用回调(callback)的dowork()方法去处理;同时client中还需要发送心跳包来通知服务端自己还在连接着服务端,发心跳包由client中keepalive()启动,由keepalivedog实现;这两个步骤由一个固定大小为2为线程池newfixedthreadpool(2)去执行,可能这里使用一个newfixedthreadpool(1)和newscheduledthreadpool(1)去处理更合理,因为心跳包是定时发的,服务端就是这样实现的(这个后续调整),client的具体代码如下(这里暴露了另外两个方法用于获取socket和当前socket所属的用户):

/**
 * 客户端
 * @author yaolin
 *
 */
public class client {
  
  private final socket socket;
  private string from;
  private final executorservice pool;
  private final callback callback;

  public client(callback callback) throws ioexception {
    this.socket = new socket(constantvalue.server_ip, constantvalue.server_port);
    this.pool = executors.newfixedthreadpool(2);
    this.callback = callback;
  }
  
  public void start() {
    pool.execute(new receivelistener(socket, callback));
  }
  
  public void keepalive(string from) {
    this.from = from;
    pool.execute(new keepalivedog(socket, from));
  }
  
  public socket getsocket() {
    return socket;
  }
  
  public string getfrom() {
    return from;
  }
}

[keepalivedog.java]

客户端在与服务端建立连接之后(该程序中是指登陆成功之后,因为登陆成功之后客户端的socket才会被服务端的socketholder管理),需要每个一段时间就给服务端发送心跳包告诉服务端自己还在跟服务端保持联系,不然服务端会在一段时间之后将没有交互的socket丢弃(详见服务端那篇博客),keepalivedog的代码实现如下(后期可能会调整为newscheduledthreadpool(1),所以这里的代码也会调整):

/**
 * keepalivedog : tell server this client is running;
 * 
 * @author yaolin
 */
public class keepalivedog implements runnable {

  private final socket socket;
  private final string from;
  
  public keepalivedog(socket socket, string from) {
    this.socket = socket;
    this.from = from;
  }

  @override
  public void run() {
    while (socket != null && !socket.isclosed()) {
      try {
        
        printwriter out = new printwriter(socket.getoutputstream());
        alivemessage message = new alivemessage();
        message.setfrom(from);
        out.println(json.tojson(message));
        out.flush();
        
        thread.sleep(constantvalue.keep_alive_period * 1000);
        
      } catch (exception e) {
        loggerutil.error("client send message failed !" + e.getmessage(), e);
      }
    }
  }
}

[receivelistener.java]

client的start()方法启动对服务端的监听由receivelistener实现,receivelistener接收到服务端的消息之后会回调callback的dowork()方法,让回调去处理具体的业务逻辑,所以receivelistener只负责监听服务端的消息,具体的处理由callback负责,这里需要提一下的是当消息类型是文件类型的时候会睡眠配置执行的间隔时间,这样callback中的dowork才能对读取来至服务端的文件流,而不是直接进入下一次循环,这里的设计跟服务端是类似的。receivelistener的具体实现代码如下:

public class receivelistener implements runnable {

  private final socket socket;
  private final callback callback;

  public receivelistener(socket socket, callback callback) {
    this.socket = socket;
    this.callback = callback;
  }

  @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());
            
            callback.dowork(socket, sb.tostring());
            basemessage message = json.parseobject(sb.tostring(), basemessage.class);
            if (message.gettype() == messagetype.file) {
              // pause to receive file
              loggerutil.trach("client:pause to receive file");
              thread.sleep(constantvalue.message_period);
            }
          } else {
            thread.sleep(constantvalue.message_period);
          }
        } catch (exception e) {
          loggerutil.error("client send message failed !" + e.getmessage(), e);
        }
      }
    }
  }

}

[callback.java、defaultcallback.java]

从上面可以看出client对消息的处理是callback回调,其callback只是一个接口,所有callback实现该接口根据自己的需要对消息进行相应地处理,这里callback默认的实现是defaultcallback,defaultcallback只对三种消息进行处理,分别是聊天消息、文件消息、返回消息。对于聊天消息,defaultcallback将通过ui中的router路由获取到相应的界面(详见下面的ui设计),然后将消息展现在对应的聊天框中;对于文件消息,defaultcallback则是将文件写入到配置中指定的路径中(这里没有通过用户的允许就接收文件,这种设计不是很友好,目前先这样);对于返回消息,defaultcallback会根据返回消息中的key叫给不同的handler去处理。具体代码如下:

 public interface callback {
   public void dowork(socket server, object data); 
 } 
public class defaultcallback implements callback {

  @override
  public void dowork(socket server, object data) {
    if (data != null) {
      basemessage message = json.parseobject(data.tostring(), basemessage.class);
      switch (message.gettype()) {
      case messagetype.chat:
        handlechatmessage(data);
        break;
      case messagetype.file:
        handlefilemessage(server, data);
        break;
      case messagetype.return:
        handlereturnmessage(data);
        break;
      }
    }
  }

  private void handlechatmessage(object data) {
    chatmessage m = json.parseobject(data.tostring(), chatmessage.class);
    string tabkey = m.getfrom();// from
    jcomponent comp = router.getview(chatroomview.class).getcomponent(chatroomview.chattabbed);
    if (comp instanceof jtabbedpane) {
      jtabbedpane tab = (jtabbedpane) comp;
      int index = tab.indexoftab(tabkey);
      if (index == -1) {
        tab.addtab(tabkey, resultholder.get(tabkey).getscrollpane());
      }
      jtextarea textarea = resultholder.get(tabkey).gettextarea();
      textarea.settext(new stringbuffer()
          .append(textarea.gettext()).append(system.lineseparator()).append(system.lineseparator())
          .append(" [").append(m.getowner()).append("] : ").append(system.lineseparator())
          .append(m.getcontent())
          .tostring());
      // scroll to bottom
      textarea.setcaretposition(textarea.gettext().length());
    }
  }

  private void handlefilemessage(socket server, object data) {
    filemessage message = json.parseobject(data.tostring(), filemessage.class);
    if (message.getsize() > 0) {
      outputstream os = null;
      try {
        if (server != null) {
          inputstream is = server.getinputstream();
          file dir = new file(constantvalue.client_receive_dir);
          if (!dir.exists()) {
            dir.mkdirs();
          }
          os = new fileoutputstream(
              new file(pathutil.combination(constantvalue.client_receive_dir, new date().gettime() + message.getname())));
          int total = 0;
          while (!server.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("receive buff [" + len + "]");
              }
              os.flush();
              if (total >= message.getsize()) {
                loggerutil.info("receive buff [ok]");
                break;
              }
            }
          }
        }
      } catch (exception e) {
        loggerutil.error("receive file failed ! " + e.getmessage(), e);
      } finally {
        if (os != null) {
          try {
            os.close();
          } catch (exception ignore) {
          }
          os = null;
        }
      }
    }
  }

  private void handlereturnmessage(object data) {
    returnmessage m = json.parseobject(data.tostring(), returnmessage.class);
    if (stringutil.isnotempty(m.getkey())) {
      switch (m.getkey()) {
      case key.notify: // notify client to update usr list
        hf.gethandler(key.notify).handle(data);
        break;
      case key.login:
        hf.gethandler(key.login).handle(data);
        break;
      case key.register:
        hf.gethandler(key.register).handle(data);
        break;
      case key.listuser:
        hf.gethandler(key.listuser).handle(data);
        break;
      case key.tip:
        hf.gethandler(key.tip).handle(data);
        break;
      }
    }
  }
}

[handler.java、hf.java、listuserhdl.java...]

handler组件负责对服务端返回消息类型的消息进行处理,defaultcallback根据不同的key将消息分发给不同的handler进行处理,这里也算一套简单的工厂组件吧,跟服务端处理接收到的数据设计是类似的,完整的类图如下:

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

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

public interface handler {
   public object handle(object obj);
 }
public class hf {

  public static handler gethandler(string key) {
    switch (key) {
    case key.notify:
      return new notifyhdl();
    case key.login:
      return new loginhdl();
    case key.register:
      return new registerhdl();
    case key.listuser:
      return new listuserhdl();
    case key.tip:
      return new tiphdl();
    }
    return null;
  }
}

public class listuserhdl implements handler {

  @override
  public object handle(object obj) {
    if (obj != null) {
      try {
        returnmessage rm = json.parseobject(obj.tostring(), returnmessage.class);
        if (rm.issuccess() && rm.getcontent() != null) {
          clientlistuserdto dto = json.parseobject(rm.getcontent().tostring(), clientlistuserdto.class);
          jcomponent comp = router.getview(chatroomview.class).getcomponent(chatroomview.listusrlist);
          if (comp instanceof jlist) {
            @suppresswarnings("unchecked") //
            jlist<string> listusrlist = (jlist<string>) comp;
            list<string> listuser = new linkedlist<string>();
            listuser.addall(dto.getlistuser());
            collections.sort(listuser);
            listuser.add(0, constantvalue.to_all);
            listusrlist.setlistdata(listuser.toarray(new string[]{}));
          }
        }
      } catch (exception e) {
        loggerutil.error("handle listusr failed! " + e.getmessage(), e);
      }
    }
    return null;
  }

}

public class loginhdl implements handler {

  @override
  public object handle(object obj) {
    if (obj != null) {
      try {
        returnmessage rm = json.parseobject(obj.tostring(),returnmessage.class);
        if (rm.issuccess()) {
          router.getview(registerandloginview.class).trash();
          router.getview(chatroomview.class).create().display();
          clientholder.getclient().keepalive(rm.getto()); // keep...
        } else {
          container container = router.getview(registerandloginview.class).container();
          if (container != null) {
            // show error
            joptionpane.showmessagedialog(container, rm.getmessage());
          }
        }
      } catch (exception e) {
        loggerutil.error("handle login failed! " + e.getmessage(), e);
      }
    }
    return null;
  }

}

public class notifyhdl implements handler {

  @override
  public object handle(object obj) {
    if (obj != null) {
      try {
        returnmessage rm = json.parseobject(obj.tostring(), returnmessage.class);
        if (rm.issuccess() && rm.getcontent() != null) {
          clientnotifydto dto = json.parseobject(rm.getcontent().tostring(), clientnotifydto.class);
          jcomponent comp = router.getview(chatroomview.class).getcomponent(chatroomview.listusrlist);
          if (comp instanceof jlist) {
            @suppresswarnings("unchecked") //
            jlist<string> listusrlist = (jlist<string>) comp;
            list<string> listuser = modeltolist(listusrlist.getmodel());
            if (dto.isflag()) {
              if (!listuser.contains(dto.getusername())) {
                listuser.add(dto.getusername());
                listuser.remove(constantvalue.to_all);
                collections.sort(listuser);
                listuser.add(0, constantvalue.to_all);
              }
            } else {
              listuser.remove(dto.getusername());
            }
            listusrlist.setlistdata(listuser.toarray(new string[]{}));
          }
        }
      } catch (exception e) {
        loggerutil.error("handle nofity failed! " + e.getmessage(), e);
      }
    }
    return null;
  }

  private list<string> modeltolist(listmodel<string> listmodel) {
    list<string> list = new linkedlist<string>();
    if (listmodel != null) {
      for (int i = 0; i < listmodel.getsize(); i++) {
        list.add(listmodel.getelementat(i));
      }
    }
    return list;
  }
}

public class registerhdl implements handler {

  @override
  public object handle(object obj) {
    if (obj != null) {
      try {
        returnmessage rm = json.parseobject(obj.tostring(),returnmessage.class);
        container container = router.getview(registerandloginview.class).container();
        if (container != null) {
          if (rm.issuccess()) {
            joptionpane.showmessagedialog(container, rm.getcontent());
          } else {
            joptionpane.showmessagedialog(container, rm.getmessage());
          }
        }
      } catch (exception e) {
        loggerutil.error("handle register failed! " + e.getmessage(), e);
      }
    }
    return null;
  }

}

public class tiphdl implements handler {

  @override
  public object handle(object obj) {
    if (obj != null) {
      try {
        returnmessage m = json.parseobject(obj.tostring(), returnmessage.class);
        if (m.issuccess() && m.getcontent() != null) {
          string tabkey = m.getfrom();
          string tip = m.getcontent().tostring();
          jcomponent comp = router.getview(chatroomview.class).getcomponent(chatroomview.chattabbed);
          if (comp instanceof jtabbedpane) {
            jtabbedpane tab = (jtabbedpane) comp;
            int index = tab.indexoftab(tabkey);
            if (index == -1) {
              tab.addtab(tabkey, resultholder.get(tabkey).getscrollpane());
            }
            jtextarea textarea = resultholder.get(tabkey).gettextarea();
            textarea.settext(new stringbuffer()
                .append(textarea.gettext()).append(system.lineseparator()).append(system.lineseparator())
                .append(" [").append(m.getowner()).append("] : ").append(system.lineseparator())
                .append(tip)
                .tostring());
            // scroll to bottom
            textarea.setcaretposition(textarea.gettext().length());
          }
        }
      } catch (exception e) {
        loggerutil.error("handle tip failed! " + e.getmessage(), e);
      }
    }
    return null;
  }

}

 对于socket通讯模块还有一个类,那就是clientholder,这个类用于存储当前client,跟服务端的socketholder是类似的。

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

  public static client client;

  public static client getclient() {
    return client;
  }

  public static void setclient(client client) {
    clientholder.client = client;
  }
}

ui模块具体实现:

上面记录了socket通讯模块的设计,接下来记录一下ui的设计模块,我不打算自己写ui,毕竟自己写出来的太丑了,所以后期可能会叫同学或朋友帮忙敲一下,所以我将ui的事件处理都交由action去处理,将ui设计和事件响应简单分离,所有ui继承jframe并实现view接口,上面的handler实现类通过router获取(存在则直接返回,不存在则创建并存储)指定的ui,view中提供了ui的创建create()、获取container()、获取ui中的组件getcomponent(),显示display(),回收trash();resultwrapper和resultholder只是为了创建和存储聊天选项卡。设计如下:

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

[router.java、view.java]

所有ui继承jframe并实现view接口,handler实现类通过router获取(存在则直接返回,不存在则创建并存储)指定的ui,view中提供了ui的创建create()、获取container()、获取ui中的组件getcomponent(),显示display(),回收trash(),具体实现如下:

/**
 * view 路由
 * @author yaolin
 */
public class router {

  private static map<string, view> listroute = new hashmap<string,view>();
  
  public static view getview(class<?> clazz) {
    view v = listroute.get(clazz.getname());
    if (v == null) {
      try {
        v = (view) class.forname(clazz.getname()).newinstance();
        listroute.put(clazz.getname(), v);
      } catch (exception e) {
        loggerutil.error("create view failed! " + e.getmessage(), e);
      }
    }
    return v;
  }
}

/**
 * 所有界面的规范接口
 * @author yaolin
 *
 */
public interface view {
  
  /**
   * 
   */
  public view create();

  /**
   * 
   */
  public container container();
  
  /**
   * @param key
   */
  public jcomponent getcomponent(string key);
  
  /**
   * 
   */
  public void display();
  
  /**
   * 
   */
  public void trash();
  
}

[registerandloginview.java、chatroomview.java]

由于不想自己写ui,我这里只是简单的写了两个ui界面,分别是注册和登陆界面、聊天界面,这里给出两个丑丑的界面:

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

注册登录界面

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

聊天界面

下面给出这两个这界面的具体代码:

/**
 * 注册、登陆
 * @author yaolin
 */
public class registerandloginview extends jframe implements view {

  private static final long serialversionuid = 6322088074312546736l;
  private final registerandloginaction action = new registerandloginaction();
  
  private static boolean create = false;
  
  @override
  public view create() {
    if (! create) {
      init();
      create = true;
    }
    return this;
  }
  
  public container container() {
    create();
    return getcontentpane();
  }
  
  @override
  public jcomponent getcomponent(string key) {
    return null;
  }
  
  @override
  public void display() {
    setvisible(true);
  }
  
  @override
  public void trash() {
    dispose();
  }
  
  
  private void init() {
    // attribute
    setsize(500, 300);
    setresizable(false);
    setlocationrelativeto(null);
    
    // container
    jpanel panel = new jpanel();
    panel.setlayout(null);
    
    // component
    // username
    jlabel lbusername = new jlabel(i18n.text_username);
    lbusername.setbounds(100, 80, 200, 30);
    final jtextfield tfusername = new jtextfield();
    tfusername.setbounds(150, 80, 230, 30);
    panel.add(lbusername);
    panel.add(tfusername);
    // passsword
    jlabel lbpassword = new jlabel(i18n.text_password);
    lbpassword.setbounds(100, 120, 200, 30);
    final jpasswordfield pfpassword = new jpasswordfield();
    pfpassword.setbounds(150, 120, 230, 30);
    panel.add(lbpassword);
    panel.add(pfpassword);
    // btnregister
    jbutton btnregister = new jbutton(i18n.btn_register);
    btnregister.setbounds(100, 175, 80, 30);
    // btnlogin
    final jbutton btnlogin = new jbutton(i18n.btn_login);
    btnlogin.setbounds(200, 175, 80, 30);
    // btncancel
    jbutton btnexit = new jbutton(i18n.btn_exit);
    btnexit.setbounds(300, 175, 80, 30);
    panel.add(btnregister);
    panel.add(btnlogin);
    panel.add(btnexit);
    
    // event
    pfpassword.addkeylistener(new keyadapter() {
      public void keypressed(final keyevent e) {
        if (e.getkeycode() == keyevent.vk_enter)
          btnlogin.doclick();
      }
    });// end of addkeylistener
    
    btnregister.addactionlistener(new actionlistener() {
      public void actionperformed(final actionevent e) {
        if (stringutil.isempty(tfusername.gettext()) 
            || stringutil.isempty(new string(pfpassword.getpassword()))) {
          joptionpane.showmessagedialog(getcontentpane(), i18n.info_register_empty_data);
          return ;
        }
        action.handleregister(tfusername.gettext(), new string(pfpassword.getpassword()));
      }
    });// end of addactionlistener
    
    btnlogin.addactionlistener(new actionlistener() {
      public void actionperformed(final actionevent e) {
        if (stringutil.isempty(tfusername.gettext()) 
            || stringutil.isempty(new string(pfpassword.getpassword()))) {
          joptionpane.showmessagedialog(getcontentpane(), i18n.info_login_empty_data);
          return ;
        }
        action.handlelogin(tfusername.gettext(), new string(pfpassword.getpassword()));
      }
    });// end of addactionlistener
    
    btnexit.addactionlistener(new actionlistener() {
      public void actionperformed(final actionevent e) {
        system.exit(0);
      }
    });// end of addactionlistener

    getcontentpane().add(panel);
    setdefaultcloseoperation(jframe.exit_on_close);
  }
}

/**
 * client 聊天窗口
 * 
 * @author yaolin
 */
public class chatroomview extends jframe implements view {

  private static final long serialversionuid = -4515831172899054818l;

  public static final string listusrlist = "listusrlist";
  public static final string chattabbed = "chattabbed";

  private static boolean create = false;
  private chatroomaction action = new chatroomaction();

  private jlist<string> listusrlist = null;
  private jtabbedpane chattabbed = null;

  @override
  public view create() {
    if (!create) {
      init();
      create = true;
    }
    return this;
  }

  public container container() {
    create();
    return getcontentpane();
  }

  @override
  public jcomponent getcomponent(string key) {
    create();
    switch (key) {
    case listusrlist:
      return listusrlist;
    case chattabbed:
      return chattabbed;
    }
    return null;
  }

  @override
  public void display() {
    setvisible(true);
  }

  @override
  public void trash() {
    dispose();
  }

  public void init() {
    settitle(i18n.text_app_name);
    setsize(800, 600);
    setresizable(false);
    setlocationrelativeto(null);

    setlayout(new borderlayout());
    add(createchatpanel(), borderlayout.center);
    add(createusrlistview(), borderlayout.east);

    setdefaultcloseoperation(jframe.exit_on_close);
  }

  private jcomponent createchatpanel() {
    // file selector
    final jfilechooser filechooser = new jfilechooser();

    jpanel panel = new jpanel(new borderlayout());
    // center
    chattabbed = new jtabbedpane();
    chattabbed.addtab(constantvalue.to_all, resultholder.get(constantvalue.to_all).getscrollpane());
    panel.add(chattabbed, borderlayout.center);

    // south
    jpanel south = new jpanel(new borderlayout());
    // south - file
    jpanel middle = new jpanel(new borderlayout());
    middle.add(new jlabel(), borderlayout.center); // just for padding
    jbutton btnupload = new jbutton(i18n.btn_send_file);
    middle.add(btnupload, borderlayout.east);
    south.add(middle, borderlayout.north);
    // south - textarea
    final jtextarea tasend = new jtextarea();
    tasend.setcaretcolor(color.blue);
    tasend.setmargin(new insets(10, 10, 10, 10));
    tasend.setrows(10);
    south.add(tasend, borderlayout.center);
    // south - btn
    jpanel bottom = new jpanel(new borderlayout());
    bottom.add(new jlabel(), borderlayout.center); // just for padding
    jbutton btnsend = new jbutton(i18n.btn_send);
    bottom.add(btnsend, borderlayout.east);

    south.add(bottom, borderlayout.south);

    btnupload.addactionlistener(new actionlistener() {
      public void actionperformed(final actionevent e) {
        if (! constantvalue.to_all.equals(chattabbed.gettitleat(chattabbed.getselectedindex()))) {
          int returnval = filechooser.showopendialog(chatroomview.this);
          if (returnval == jfilechooser.approve_option) {
            file file = filechooser.getselectedfile();
            action.upload(chattabbed.gettitleat(chattabbed.getselectedindex()), file);
          }
        } else {
          joptionpane.showmessagedialog(getcontentpane(), i18n.info_file_to_all_error);
        }
      }
    });

    btnsend.addactionlistener(new actionlistener() {
      public void actionperformed(final actionevent e) {
        if (stringutil.isnotempty(tasend.gettext())) {
          action.send(chattabbed.gettitleat(chattabbed.getselectedindex()), tasend.gettext());
          tasend.settext(null);
        }
      }
    });

    panel.add(south, borderlayout.south);
    return panel;
  }

  private jcomponent createusrlistview() {
    listusrlist = new jlist<string>();
    listusrlist.setborder(new lineborder(color.blue));
    listusrlist.setlistdata(new string[] { constantvalue.to_all });
    listusrlist.setfixedcellwidth(200);
    listusrlist.setfixedcellheight(30);
    listusrlist.addlistselectionlistener(new listselectionlistener() {
      @override
      public void valuechanged(listselectionevent e) { // chat to
        if (chattabbed.indexoftab(listusrlist.getselectedvalue()) == -1
            && listusrlist.getselectedvalue() != null
            && !listusrlist.getselectedvalue().equals(clientholder.getclient().getfrom())) {
          chattabbed.addtab(listusrlist.getselectedvalue(),
              resultholder.get(listusrlist.getselectedvalue()).getscrollpane());
          chattabbed.setselectedindex(chattabbed.indexoftab(listusrlist.getselectedvalue()));
        }
      }
    });
    return listusrlist;
  }
}

[registerandloginaction.java、chatroomaction.java]

这里ui的事件处理都交由action去处理,将ui设计和事件响应简单分离,registerandloginview的事件由registerandloginaction处理,chatroomview的事件由chatroomaction处理。具体实现如下:

public class registerandloginaction {

  public void handleregister(string username, string password) {
    if (stringutil.isempty(username) || stringutil.isempty(password)) {
      return;
    }
    registermessage message = new registermessage()
        .setusername(username)
        .setpassword(password);
    message.setfrom(username);
    sendhelper.send(clientholder.getclient().getsocket(), message);
  }
  
  
  public void handlelogin(string username, string password) {
    if (stringutil.isempty(username) || stringutil.isempty(password)) {
      return;
    }
    loginmessage message = new loginmessage()
        .setusername(username)
        .setpassword(password);
    message.setfrom(username);
    sendhelper.send(clientholder.getclient().getsocket(), message);
  }
}

对于ui设计还有两个类,分别是resultholder和resultwrapper,resultwrapper和resultholder只是为了创建和存储聊天选项卡,具体实现如下:

public class resultwrapper {
  
  private jscrollpane scrollpane;
  private jtextarea textarea;
  
  public resultwrapper(jscrollpane scrollpane, jtextarea textarea) {
    this.scrollpane = scrollpane;
    this.textarea = textarea;
  }
  public jscrollpane getscrollpane() {
    return scrollpane;
  }
  public void setscrollpane(jscrollpane scrollpane) {
    this.scrollpane = scrollpane;
  }
  public jtextarea gettextarea() {
    return textarea;
  }
  public void settextarea(jtextarea textarea) {
    this.textarea = textarea;
  }
}
public class resultholder {

  private static map<string, resultwrapper> listresultwrapper = new hashmap<string,resultwrapper>();
  
  public static void put(string key, resultwrapper wrapper) {
    listresultwrapper.put(key, wrapper);
  }
  
  public static resultwrapper get(string key) {
    resultwrapper wrapper = listresultwrapper.get(key);
    if (wrapper == null) {
      wrapper = create();
      put(key, wrapper);
    }
    return wrapper;
  }
  
  
  private static resultwrapper create() {
    jtextarea resulttextarea = new jtextarea();
    resulttextarea.seteditable(false);
    resulttextarea.setborder(new lineborder(color.blue));
    jscrollpane scrollpane = new jscrollpane(resulttextarea);
    scrollpane.sethorizontalscrollbarpolicy(scrollpaneconstants.horizontal_scrollbar_never);
    scrollpane.setverticalscrollbarpolicy(scrollpaneconstants.vertical_scrollbar_as_needed);
    resultwrapper wrapper = new resultwrapper(scrollpane, resulttextarea);
    return wrapper;
  }
}

最后的最后给出,客户端运行的入口:

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

  public static void main(string[] args) {
    view v = router.getview(registerandloginview.class).create();
    try {
      v.display();
      client client = new client(new defaultcallback());
      client.start();
      clientholder.setclient(client);
    } catch (ioexception e) {
      joptionpane.showmessagedialog(v.container(), e.getmessage());
    }
  }
}

demo下载地址:

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