首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WCF 實作聊天程式:雙工通訊、ChannelFactory 動態代理與事件驅動架構

     編輯:關於.NET

架構設計:每個執行個體皆為 Client/Server

採用 NetTcpBinding,每個應用程式同時裝載服務 (Server) 與呼叫遠端服務 (Client);無需 Add Service Reference,直接共用合約組件,使用 ChannelFactory<T> 動態建立通道。

服務合約與實作

[ServiceContract]
public interface IService
{
    [OperationContract(IsOneWay = true)]
    void SendMessage(string msg);
}

public class MyChatService : IService
{
    // 事件橋接:服務層 → UI 層
    public event EventHandler<MessageReceiveEventArgs> MessageGot;

    public MyChatService()
    {
        MessageGot += Form1.GetMessageCallBack; // 靜態回呼
    }

    public void SendMessage(string msg)
    {
        if (MessageGot != null)
            MessageGot(this, new MessageReceiveEventArgs(msg));
    }
}

public class MessageReceiveEventArgs : EventArgs
{
    public string MessageText { get; private set; }
    public MessageReceiveEventArgs(string message) { MessageText = message; }
}

UI 層事件處理與靜態實例模式

public partial class Form1 : Form
{
    static Form1 CurrentInstance = null; // 靜態持有目前視窗實例

    public Form1() { InitializeComponent(); CurrentInstance = this; }

    // 靜態回呼:服務執行緒觸發 → 透過 CurrentInstance 跨執行緒更新 UI
    public static void GetMessageCallBack(object sender, MessageReceiveEventArgs e)
    {
        if (CurrentInstance != null)
            CurrentInstance.AddMessageToListBox(e.MessageText); // 需 Invoke/BeginInvoke
    }

    void AddMessageToListBox(string msg)
    {
        if (listBox1.InvokeRequired)
            listBox1.BeginInvoke(new Action(AddMessageToListBox), msg);
        else
            listBox1.Items.Add(msg);
    }
}

服務裝載與通道建立

ServiceHost _host;
void OpenService(int port)
{
    _host = new ServiceHost(typeof(MyChatService));
    var binding = new NetTcpBinding { Security = { Mode = SecurityMode.None } };
    _host.AddServiceEndpoint(typeof(IService), binding, $"net.tcp://{Dns.GetHostName()}:{port}/chatsvc/");
    _host.Opened += (s, e) => ShowMessage("服務已啟動");
    _host.Open();
}

void CloseService()
{
    if (_host != null) { _host.Close(); _host = null; }
}

發送訊息:ChannelFactory 動態代理

void SendMessage(string remoteHost, int port, string text)
{
    var binding = new NetTcpBinding { Security = { Mode = SecurityMode.None } };
    var address = new EndpointAddress($"net.tcp://{remoteHost}:{port}/chatsvc/");
    var channel = ChannelFactory<IService>.CreateChannel(binding, address);
    try
    {
        ((IService)channel).SendMessage(text);
    }
    catch (Exception ex) { ShowMessage(ex.Message); }
    finally { ((ICommunicationObject)channel).Close(); }
}

關鍵優勢

  • 無 WSDL/Proxy 產生:共用合約 DLL,ChannelFactory 運行時建立透明代理。
  • IsOneWay = true:火燭式呼叫,發送端不等待回應,適合聊天廣播。
  • 事件解耦:服務實作不參考 UI,透過靜態事件回呼實現跨層通知。
  • NetTcpBinding:二進位編碼、連線導向、效能優於 HTTP 綁定。

擴充方向

  1. 檔案傳輸:利用 Stream 傳輸大型二進位資料,配合 TransferMode.Streamed。
  2. 雙工回呼:WSDualHttpBinding 或 NetTcpBinding + CallbackContract 實現伺服器主動推播。
  3. 安全性:SecurityMode.Transport + Windows 認證/憑證。

總結

WCF 以合約優先、配置驅動、多種綁定支援,大幅降低網路通訊開發複雜度。聊天程式展示了「共用合約 + ChannelFactory + 事件橋接」的輕量級雙角色架構,適合 P2P、即時通訊、分散式協作等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved