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

分享WCF聊天程序--WCFChat实现代码

程序员文章站 2024-01-24 12:31:46
无意中在一个国外的站点下到了一个利用wcf实现聊天的程序,作者是:nikola paljetak。研究了一下,自己做了测试和部分修改,感觉还不错,分享给大家。 先来看下运...

无意中在一个国外的站点下到了一个利用wcf实现聊天的程序,作者是:nikola paljetak。研究了一下,自己做了测试和部分修改,感觉还不错,分享给大家。
先来看下运行效果:
开启服务:
分享WCF聊天程序--WCFChat实现代码
客户端程序:
分享WCF聊天程序--WCFChat实现代码
分享WCF聊天程序--WCFChat实现代码
程序分为客户端和服务器端:

------------服务器端:

ichatservice.cs:

using system;
using system.collections.generic;
using system.linq;
using system.runtime.serialization;
using system.servicemodel;
using system.text;
using system.collections;

namespace wcfchatservice
{
  // sessionmode.required 允许session会话。双工协定时的回调协定类型为ichatcallback接口
  [servicecontract(sessionmode = sessionmode.required, callbackcontract = typeof(ichatcallback))]
  public interface ichatservice
  {
    [operationcontract(isoneway = false, isinitiating = true, isterminating = false)]//----->isoneway = false等待服务器完成对方法处理;isinitiating = true启动session会话,isterminating = false 设置服务器发送回复后不关闭会话
    string[] join(string name);//用户加入

    [operationcontract(isoneway = true, isinitiating = false, isterminating = false)]
    void say(string msg);//群聊信息

    [operationcontract(isoneway = true, isinitiating = false, isterminating = false)]
    void whisper(string to, string msg);//私聊信息

    [operationcontract(isoneway = true, isinitiating = false, isterminating = true)]
    void leave();//用户加入
  }
  /// <summary>
  /// 双向通信的回调接口
  /// </summary>
  interface ichatcallback
  {
    [operationcontract(isoneway = true)]
    void receive(string sendername, string message);

    [operationcontract(isoneway = true)]
    void receivewhisper(string sendername, string message);

    [operationcontract(isoneway = true)]
    void userenter(string name);

    [operationcontract(isoneway = true)]
    void userleave(string name);
  }

  /// <summary>
  /// 设定消息的类型
  /// </summary>
  public enum messagetype { receive, userenter, userleave, receivewhisper };
  /// <summary>
  /// 定义一个本例的事件消息类. 创建包含有关事件的其他有用的信息的变量,只要派生自eventargs即可。
  /// </summary>
  public class chateventargs : eventargs
  {
    public messagetype msgtype;
    public string name;
    public string message;
  }
}

chatservice.cs

using system;
using system.collections.generic;
using system.linq;
using system.runtime.serialization;
using system.servicemodel;
using system.text;

namespace wcfchatservice
{
  // instancecontextmode.persession 服务器为每个客户会话创建一个新的上下文对象。concurrencymode.multiple 异步的多线程实例
  [servicebehavior(instancecontextmode = instancecontextmode.persession, concurrencymode = concurrencymode.multiple)]
  public class chatservice : ichatservice
  {
    private static object syncobj = new object();////定义一个静态对象用于线程部份代码块的锁定,用于lock操作
    ichatcallback callback = null;

    public delegate void chateventhandler(object sender, chateventargs e);//定义用于把处理程序赋予给事件的委托。
    public static event chateventhandler chatevent;//定义事件
    static dictionary<string, chateventhandler> chatters = new dictionary<string, chateventhandler>();//创建一个静态dictionary(表示键和值)集合(字典),用于记录在线成员,dictionary<(of <(tkey, tvalue>)>) 泛型类

    private string name;
    private chateventhandler myeventhandler = null;


    public string[] join(string name)
    {
      bool useradded = false;
      myeventhandler = new chateventhandler(myeventhandler);//将myeventhandler方法作为参数传递给委托

      lock (syncobj)//线程的同步性,同步访问多个线程的任何变量,利用lock(独占锁),确保数据访问的唯一性。
      {
        if (!chatters.containskey(name) && name != "" && name != null)
        {
          this.name = name;
          chatters.add(name, myeventhandler);
          useradded = true;
        }
      }

      if (useradded)
      {
        callback = operationcontext.current.getcallbackchannel<ichatcallback>();//获取当前操作客户端实例的通道给ichatcallback接口的实例callback,此通道是一个定义为ichatcallback类型的泛类型,通道的类型是事先服务契约协定好的双工机制。
        chateventargs e = new chateventargs();//实例化事件消息类chateventargs
        e.msgtype = messagetype.userenter;
        e.name = name;
        broadcastmessage(e);
        chatevent += myeventhandler;
        string[] list = new string[chatters.count]; //以下代码返回当前进入聊天室成员的称列表
        lock (syncobj)
        {
          chatters.keys.copyto(list, 0);//将字典中记录的用户信息复制到数组中返回。
        }
        return list;
      }
      else
      {
        return null;
      }
    }

    public void say(string msg)
    {
      chateventargs e = new chateventargs();
      e.msgtype = messagetype.receive;
      e.name = this.name;
      e.message = msg;
      broadcastmessage(e);
    }

    public void whisper(string to, string msg)
    {
      chateventargs e = new chateventargs();
      e.msgtype = messagetype.receivewhisper;
      e.name = this.name;
      e.message = msg;
      try
      {
        chateventhandler chatterto;//创建一个临时委托实例
        lock (syncobj)
        {
          chatterto = chatters[to]; //查找成员字典中,找到要接收者的委托调用
        }
        chatterto.begininvoke(this, e, new asynccallback(endasync), null);//异步方式调用接收者的委托调用
      }
      catch (keynotfoundexception)
      {
      }
    }

    public void leave()
    {
      if (this.name == null)
        return;

      lock (syncobj)
      {
        chatters.remove(this.name);
      }
      chatevent -= myeventhandler;
      chateventargs e = new chateventargs();
      e.msgtype = messagetype.userleave;
      e.name = this.name;
      this.name = null;
      broadcastmessage(e);
    }

    //回调,根据客户端动作通知对应客户端执行对应的操作
    private void myeventhandler(object sender, chateventargs e)
    {
      try
      {
        switch (e.msgtype)
        {
          case messagetype.receive:
            callback.receive(e.name, e.message);
            break;
          case messagetype.receivewhisper:
            callback.receivewhisper(e.name, e.message);
            break;
          case messagetype.userenter:
            callback.userenter(e.name);
            break;
          case messagetype.userleave:
            callback.userleave(e.name);
            break;
        }
      }
      catch
      {
        leave();
      }
    }

    private void broadcastmessage(chateventargs e)
    {

      chateventhandler temp = chatevent;

      if (temp != null)
      {
        //循环将在线的用户广播信息
        foreach (chateventhandler handler in temp.getinvocationlist())
        {
          //异步方式调用多路广播委托的调用列表中的chateventhandler 
          handler.begininvoke(this, e, new asynccallback(endasync), null);
        }
      }
    }
    //广播中线程调用完成的回调方法功能:清除异常多路广播委托的调用列表中异常对象(空对象)
    private void endasync(iasyncresult ar)
    {
      chateventhandler d = null;

      try
      {
        //封装异步委托上的异步操作结果
        system.runtime.remoting.messaging.asyncresult asres = (system.runtime.remoting.messaging.asyncresult)ar;
        d = ((chateventhandler)asres.asyncdelegate);
        d.endinvoke(ar);
      }
      catch
      {
        chatevent -= d;
      }
    }
  }
}

------------客户端:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
using system.servicemodel;

namespace wcfchatclient
{
  public partial class chatform : form, ichatservicecallback
  {
    /// <summary>
    /// 该函数将指定的消息发送到一个或多个窗口。此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回。 
    /// </summary>
    /// <param name="hwnd">其窗口程序将接收消息的窗口的句柄</param>
    /// <param name="msg">指定被发送的消息</param>
    /// <param name="wparam">指定附加的消息指定信息</param>
    /// <param name="lparam">指定附加的消息指定信息</param>
    [dllimport("user32.dll")]
    private static extern int sendmessage(intptr hwnd, int msg, int wparam, intptr lparam);
    //当一个窗口标准垂直滚动条产生一个滚动事件时发送此消息给那个窗口,也发送给拥有它的控件
    private const int wm_vscroll = 0x115;
    private const int sb_bottom = 7;
    private int lastselectedindex = -1;

    private chatserviceclient proxy;
    private string username;

    private waitform wfdlg = new waitform();
    private delegate void handledelegate(string[] list);
    private delegate void handleerrordelegate();

    public chatform()
    {
      initializecomponent();
      showinterchatmenuitem(true);
    }

    /// <summary>
    /// 连接服务器
    /// </summary>
    private void interchatmenuitem_click(object sender, eventargs e)
    {
      lbonlineusers.items.clear();
      loginform logindlg = new loginform();
      if (logindlg.showdialog() == dialogresult.ok)
      {
        username = logindlg.txtusername.text;
        logindlg.close();
      }

      txtchatcontent.focus();
      application.doevents();
      instancecontext site = new instancecontext(this);//为实现服务实例的对象进行初始化
      proxy = new chatserviceclient(site);
      iasyncresult iar = proxy.beginjoin(username, new asynccallback(onendjoin), null);
      wfdlg.showdialog();
    }

    private void onendjoin(iasyncresult iar)
    {
      try
      {
        string[] list = proxy.endjoin(iar);
        handleendjoin(list);

      }
      catch (exception e)
      {
        handleendjoinerror();
      }

    }
    /// <summary>
    /// 错误提示
    /// </summary>
    private void handleendjoinerror()
    {
      if (wfdlg.invokerequired)
        wfdlg.invoke(new handleerrordelegate(handleendjoinerror));
      else
      {
        wfdlg.showerror("无法连接聊天室!");
        exitchatsession();
      }
    }
    /// <summary>
    /// 登录结束后的处理
    /// </summary>
    /// <param name="list"></param>
    private void handleendjoin(string[] list)
    {
      if (wfdlg.invokerequired)
        wfdlg.invoke(new handledelegate(handleendjoin), new object[] { list });
      else
      {
        wfdlg.visible = false;
        showinterchatmenuitem(false);
        foreach (string name in list)
        {
          lbonlineusers.items.add(name);
        }
        appendtext(" 用户: " + username + "--------登录---------" + datetime.now.tostring()+ environment.newline);
      }
    }
    /// <summary>
    /// 退出聊天室
    /// </summary>
    private void outinterchatmenuitem_click(object sender, eventargs e)
    {
      exitchatsession();
      application.exit();
    }
    /// <summary>
    /// 群聊
    /// </summary>
    private void btnchat_click(object sender, eventargs e)
    {
      sayandclear("", txtchatcontent.text, false);
      txtchatcontent.focus();
    }
    /// <summary>
    /// 发送消息
    /// </summary>
    private void sayandclear(string to, string msg, bool pvt)
    {
      if (msg != "")
      {
        try
        {
          communicationstate cs = proxy.state;
          //pvt 公聊还是私聊
          if (!pvt)
          {
            proxy.say(msg);
          }
          else
          {
            proxy.whisper(to, msg);
          }

          txtchatcontent.text = "";
        }
        catch
        {
          abortproxyandupdateui();
          appendtext("失去连接: " + datetime.now.tostring() + environment.newline);
          exitchatsession();
        }
      }
    }
    private void txtchatcontent_keypress(object sender, keypresseventargs e)
    {
      if (e.keychar == 13)
      {
        e.handled = true;
        btnchat.performclick();
      }
    }
    /// <summary>
    /// 只有选择一个用户时,私聊按钮才可用
    /// </summary>
    private void lbonlineusers_selectedindexchanged(object sender, eventargs e)
    {
      adjustwhisperbutton();
    }
    /// <summary>
    /// 私聊
    /// </summary>    
    private void btnwhisper_click(object sender, eventargs e)
    {
      if (txtchatdetails.text == "")
      {
        return;
      }
      object to = lbonlineusers.selecteditem;
      if (to != null)
      {
        string receivername = (string)to;
        appendtext("私下对" + receivername + "说: " + txtchatcontent.text);//+ environment.newline
        sayandclear(receivername, txtchatcontent.text, true);
        txtchatcontent.focus();
      }
    }
    /// <summary>
    /// 连接聊天室
    /// </summary>
    private void showinterchatmenuitem(bool show)
    {
      interchatmenuitem.enabled = show;
      outinterchatmenuitem.enabled = this.btnchat.enabled = !show;
    }
    private void appendtext(string text)
    {
      txtchatdetails.text += text;
      sendmessage(txtchatdetails.handle, wm_vscroll, sb_bottom, new intptr(0));
    }
    /// <summary>
    /// 退出应用程序时,释放使用资源
    /// </summary>
    private void exitchatsession()
    {
      try
      {
        proxy.leave();
      }
      catch { }
      finally
      {
        abortproxyandupdateui();
      }
    }
    /// <summary>
    /// 释放使用资源
    /// </summary>
    private void abortproxyandupdateui()
    {
      if (proxy != null)
      {
        proxy.abort();
        proxy.close();
        proxy = null;
      }
      showinterchatmenuitem(true);
    }
    /// <summary>
    /// 接收消息
    /// </summary>
    public void receive(string sendername, string message)
    {
      appendtext(sendername + "说: " + message + environment.newline);
    }
    /// <summary>
    /// 接收私聊消息
    /// </summary>
    public void receivewhisper(string sendername, string message)
    {
      appendtext(sendername + " 私下说: " + message + environment.newline);
    }
    /// <summary>
    /// 新用户登录
    /// </summary>
    public void userenter(string name)
    {
      appendtext("用户 " + name + " --------登录---------" + datetime.now.tostring() + environment.newline);
      lbonlineusers.items.add(name);
    }
    /// <summary>
    /// 用户离开
    /// </summary>
    public void userleave(string name)
    {
      appendtext("用户 " + name + " --------离开---------" + datetime.now.tostring() + environment.newline);
      lbonlineusers.items.remove(name);
      adjustwhisperbutton();
    }
    /// <summary>
    /// 控制私聊按钮的可用性,只有选择了用户时按钮才可用
    /// </summary>
    private void adjustwhisperbutton()
    {
      if (lbonlineusers.selectedindex == lastselectedindex)
      {
        lbonlineusers.selectedindex = -1;
        lastselectedindex = -1;
        btnwhisper.enabled = false;
      }
      else
      {
        btnwhisper.enabled = true;
        lastselectedindex = lbonlineusers.selectedindex;
      }

      txtchatcontent.focus();
    }
    /// <summary>
    /// 窗体关闭时,释放使用资源
    /// </summary>
    private void chatform_formclosed(object sender, formclosedeventargs e)
    {
      abortproxyandupdateui();
      application.exit();
    }
  }
}

代码中我做了详细的讲解,相信园友们完全可以看懂。代码中的一些使用的方法还是值得大家参考学习的。这里涉及到了wcf的使用方法,需要注意的是:如果想利用工具生成代理类,需要加上下面的代码:

if (host.description.behaviors.find<system.servicemodel.description.servicemetadatabehavior>() == null)
      {
        bindingelement metaelement = new tcptransportbindingelement();
        custombinding metabind = new custombinding(metaelement);
        host.description.behaviors.add(new system.servicemodel.description.servicemetadatabehavior());
        host.addserviceendpoint(typeof(system.servicemodel.description.imetadataexchange), metabind, "mex");
      }

否则在生成代理类的时候会报错如下的错误:

分享WCF聊天程序--WCFChat实现代码

源码下载:
/files/gaoweipeng/wcfchat.rar