新生命网络库客户端用法示例


/*
*	景裔	2017-03-18	创建添加
*/

class Program
    {
        private static ISocketClient _client;

        static void Main(string[] args)
        {
            XTrace.UseConsole(); //向控制台输出XTrace的日志消息

            _client = new NetUri("tcp://127.0.0.1:5689").CreateRemote();
            _client.Received += Client_Received;
            _client.Opened += Client_Opened;
            _client.Closed += Client_Closed;
            _client.Error += Client_Error;
            _client.OnDisposed += _client_OnDisposed;
            _client.Open();

            Thread.Sleep(-1);

        }

        /// <summary>
        /// 连接释放事件处理代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void _client_OnDisposed(object sender, EventArgs e)
        {
            XTrace.WriteLine("客户端资源释放。");
        }

        /// <summary>
        /// 连接过程是代码出错事件处理代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Client_Error(object sender, NewLife.ExceptionEventArgs e)
        {
            XTrace.WriteLine("------------------");
            XTrace.WriteException(e.Exception);
            XTrace.WriteLine("------------------");
        }

        /// <summary>
        /// 服务短被关闭事件处理代码(特别注意:不是断网,断网是不会触发Client_Closed的)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Client_Closed(object sender, EventArgs e)
        {
            XTrace.WriteLine("与服务器连接中断");
	    //业务逻辑代码
        }

        /// <summary>
        /// 成功连接服务器事件处理代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Client_Opened(object sender, EventArgs e)
        {
            XTrace.WriteLine("服务器({0})连接成功。", _client.Remote);
            XTrace.WriteLine("是否异步接收:{0}", _client.UseReceiveAsync);
	    //业务逻辑代码
        }


        /// <summary>
        /// 接收到的数据处理事件处理代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Client_Received(object sender, ReceivedEventArgs e)
        {
            XTrace.WriteLine("收到服务器传来的数据,长度为{0}",e.Length);
            //业务逻辑代码
        }





    }
上次更新: 2018-8-22 23:09:55