採用 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; }
}
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; }
}
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(); }
}
ChannelFactory 運行時建立透明代理。Stream 傳輸大型二進位資料,配合 TransferMode.Streamed。WSDualHttpBinding 或 NetTcpBinding + CallbackContract 實現伺服器主動推播。SecurityMode.Transport + Windows 認證/憑證。WCF 以合約優先、配置驅動、多種綁定支援,大幅降低網路通訊開發複雜度。聊天程式展示了「共用合約 + ChannelFactory + 事件橋接」的輕量級雙角色架構,適合 P2P、即時通訊、分散式協作等場景。