了解委托流程

时间:2015-02-27 08:29:45

标签: c# .net sockets delegates tcplistener

首先,我想道歉,如果这似乎我不应该发布这个问题。自从过去两周以来,我一直在努力去理解这段代码,但一切都无济于事。

我的主要问题是了解这个代表如何在这里工作

messageInformer = new MessageInformer(this.Broadcast);

我无法使用调试器来跟踪代码,因为VS不会让我这样做。我理解Socket连接,发送和接收,但我不知道代表如何在这里工作。从我注意到,在将多个客户端连接到服务器之后,当客户端向服务器发送消息时,其他客户端获得与服务器相同的消息

我理解委托是一个函数指针,我知道委托的基础知识。

有人可以向我解释一下这个代表的使用方式吗?

查找以下所有代码:

Server.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace SimpleChatServer.Communication
{
    class Server
    {
        private Socket serverSock;
        private List<ClientHandler> clientsConnected = new List<ClientHandler>();
        private MessageInformer messageInformer;
        public Server()
        {
            serverSock = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);
            Console.WriteLine("Socket created");
            serverSock.Bind(
              new IPEndPoint(IPAddress.Loopback, 8055));
            Console.WriteLine("Binding done");
            serverSock.Listen(5);
            Console.WriteLine("Listening started");
            messageInformer = new MessageInformer(this.Broadcast);
        }

        public void StartAccepting()
        {

            while (true)
            {
                clientsConnected.Add(new ClientHandler(serverSock.Accept(), messageInformer));
                Thread thread = new Thread(new ParameterizedThreadStart(clientsConnected.Last().StartReceiving));
                thread.Start();
                Console.WriteLine("New Client accepted");
            }
        }


        private void Broadcast(Socket caller, string message)
        {
            foreach (var item in clientsConnected)
            {
                if(!item.ClientSock.Equals(caller))
                item.ClientSock.Send(Encoding.UTF8.GetBytes(message));
            }
        }

    }
}

ClientHandler.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace SimpleChatServer.Communication
{
    class ClientHandler
    {
        private Socket clientSock;
        private MessageInformer informer;

        public Socket ClientSock
        {
            get { return clientSock; }
            //set { clientSock = value; }
        }

        private byte[] buffer = new byte[512];

        public ClientHandler(Socket clientSock, MessageInformer informer)
        {
            this.clientSock = clientSock;
            this.informer = informer;


        }

        /// <summary>
        ///  Receive messages from the client
        /// </summary>
        /// <param name="obj"></param>
        public void StartReceiving(object obj)
        {
            int length;
            string name = "";
            string message = "";

            #region  Handle Name
            do
            {
                length = clientSock.Receive(buffer);
                name += Encoding.UTF8.GetString(buffer, 0, length);

            } while (!name.Contains("\r\n"));

            name = name.Substring(0, name.Length - 2);

            clientSock.Send(Encoding.UTF8.GetBytes("hello " + name + "\r\n"));

            #endregion 

            while (true)
            {
                length = clientSock.Receive(buffer);
                message += Encoding.UTF8.GetString(buffer, 0, length);
                if (message.Contains("\r\n"))
                {

                    Console.Write(name + ": " + message);
                    informer(clientSock, name + ": " + message);
                    message = "";

                }
            }

        }
    }
}

Delegaters.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace SimpleChatServer.Communication
{
  public delegate void  MessageInformer(Socket caller, string message);
}

Program.cs的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleChatServer.Communication;

namespace SimpleChatServer
{
    class Program
    {
        static void Main(string[] args)
        {

            Server server = new Server();
            server.StartAccepting();
            server.StartAccepting();
            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

让我们从上到下开始:

public delegate void  MessageInformer(Socket caller, string message);

这是委托定义,此处尚未完成任何工作。

messageInformer = new MessageInformer(this.Broadcast);

这将私有变量messageInformer(具有MessageInformer委托类型)设置为新值:一个实例化的委托,以此类为目标的方法广播。必须具有与委托类型相同的参数作为此委托的目标。比较这些参数:

public delegate **void**  MessageInformer(**Socket** caller, **string** message);
private **void** Broadcast(**Socket** caller, **string** message)

调用messageInformer(mySocket, myMessage);现在将调用重定向到Server.Broadcast(mySocket, MyMessage),无论调用此委托的位置如何,因为此委托绑定到Server的Broadcast方法的实例,而不依赖于它的上下文被称为。

clientsConnected.Add(new ClientHandler(serverSock.Accept(), messageInformer));

此行创建一个带有新连接套接字的新ClientHandler,并为其提供messageInformerDelegate,即使现在将其提供给ClientHandler,仍然指向Server.Broadcast。然后将委托保存为ClientHandler中的informer

informer(clientSock, name + ": " + message);

ClientHandler.StartReceiving方法中的这一行现在调用Server.BroadCast方法,提供它自己的套接字及其收到的消息。如果您在ClientHandler中拥有对服务器的引用,则可以将其链接到myServer.Broadcast(clientSock, name + ": "+ message);

然后,Server.Broadcast方法循环遍历所有套接字,并转发已获取的消息,并检查委托调用提供的Socket(在这种情况下始终是调用Clienthandler的套接字)是否是此消息所在的套接字转发给。