当前位置:编程学习 > C#/ASP.NET >>

自定义事件的使用例程

答案:自定义事件的使用例程

蓝色力量 cnhai@21cn.com 转贴请注明:开发者俱乐部(http://www.dev-club.com)

2002.1.22
这段程序运用一个sever类设计一个聊天室:
//此类为服务器类-用于与客户端的通信,其中构造了几个自定义事件
using System;using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace sockchat
{
    public delegate void EventServerStartHandler(EventServerStartArgs e);  //声明代理
    public delegate void EventClientContextHandler(EventClientContextArgs e);
    public class EventClientContextArgs //构造自定义事件类
    {
        public string IP;
        public EventClientContextArgs(string _ip)
        {
            IP = _ip;
        }
    }
    public class EventServerStartArgs :EventArgs
    {
        public string returnstring;
        public EventServerStartArgs()
        {
            returnstring = "服务器已启动";
        }        
    }

        public class server
        {
            public event EventServerStartHandler SStartEvent;
            public event EventClientContextHandler CcontextEvent;
            private TcpListener tcpserver;
            private Thread thread;
            private int _port;
            private Socket socket;
            public int port
            {
                get
                {
                    return _port;
                }
            }
            public server(int c_port)
            {
                _port = c_port;
                tcpserver = new TcpListener(_port);
                thread = null;
            }
            public bool start()
            {
                
                bool s = false;
                try
                {
                    tcpserver.Start();                    
                    thread = new Thread(new ThreadStart(this.listener));
                    thread.Start();
                    s = true;
                }
                catch(System.Exception e)
                {
                    s = false;
                }
                if(s)
                {
                    this.SStartEvent(new EventServerStartArgs());
                }
                else
                {
                    
                }
                
                return s;
            }
            public void listener()
            {
                while(true)
                {
                    clientcontent(tcpserver.AcceptSocket());
                    
                }
            }
            public void clientcontent(Socket s)
            {
          

上一个:Using the Remoting Callbacks in .Net Applications
下一个:对虚拟的看法

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,