程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#編寫簡單的聊天程序(6)

C#編寫簡單的聊天程序(6)

編輯:關於C語言

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 {
        }
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved