3.實現Talker類
Talker類是最平庸的一個類,它的全部功能就是將操作委托給實際的IMessageReceiver和IMessageSender。定義這兩個接口的好處也從這裡 可以看出來:如果日後想重新實現這個程序,所有Windows窗體的代碼和Talker的代碼都不需要修改,只需要針對這兩個接口編程就可以了。
public class Talker {
private IMessageReceiver receiver;
private IMessageSender sender;
public Talker(IMessageReceiver receiver, IMessageSender sender) {
this.receiver = receiver;
this.sender = sender;
}
public Talker() {
this.receiver = new MessageReceiver();
this.sender = new MessageSender();
}
public event MessageReceivedEventHandler MessageReceived {
add {
receiver.MessageReceived += value;
}
remove {
receiver.MessageReceived -= value;
}
}
public event ClientConnectedEventHandler ClIEntConnected {
add {
receiver.ClIEntConnected += value;
}
remove {
receiver.ClIEntConnected -= value;
}
}
public event ConnectionLostEventHandler ClIEntLost {
add {
receiver.ClIEntLost += value;
}
remove {
receiver.ClIEntLost -= value;
}
}
// 注意這個事件
public event PortNumberReadyEventHandler PortNumberReady {
add {
((MessageReceiver)receiver).PortNumberReady += value;
}
remove {
((MessageReceiver)receiver).PortNumberReady -= value;
}
}
// 連接遠程 - 使用主機名
public bool ConnectByHost(string hostName, int port) {
IPAddress[] ips = Dns.GetHostAddresses(hostName);
return sender.Connect(ips[0], port);
}
// 連接遠程 - 使用IP
public bool ConnectByIp(string ip, int port) {
IPAddress ipAddress;
try {
ipAddress = IPAddress.Parse(ip);
} catch {
return false;
}
return sender.Connect(ipAddress, port);
}
// 發送消息
public bool SendMessage(Message msg) {
return sender.SendMessage(msg);
}
// 釋放資源,停止偵聽
public void Dispose() {
try {
sender.SignOut();
receiver.StopListen();
} catch {
}
}
// 注銷
public void SignOut() {
try {
sender.SignOut();
} catch {
}
}
}