Example #1
0
        /// <summary></summary>
        public void EnsureServer()
        {
            if (Server == null)
            {
                if (ProtocolType == NetType.Tcp)
                {
                    var server = new TcpServer();
                    Server = server;
                    //server.ReuseAddress = true;
                    server.NewSession += server_Accepted;
                }
                else
                {
                    var server = new UdpServer();
                    //Server = server;
                    //server.ReuseAddress = true;
                    server.Received += server_Received;
                    //server.Bind();
                    server.Open();
                }

                Server.Start();

                WriteLog("监听:{0}", Server);
            }
        }
Example #2
0
        /// <summary>开始</summary>
        public void Start()
        {
            if (Client == null)
            {
                Client           = new UdpServer();
                Client.Received += Client_Received;
                Client.Open();

                _Timer = new TimerX(s =>
                {
                    try
                    {
                        SendDiscover();
                    }
                    catch (Exception ex) { WriteLog(ex.ToString()); }
                }, null, 0, 1000);
            }

            //var rnd = new Random();
            TransID = Rand.Next();
            if (_Mac == null || _Mac.Length == 0)
            {
                _Mac = NetHelper.GetMacs().FirstOrDefault();
            }
            if (_Mac == null || _Mac.Length == 0)
            {
                _Mac = Rand.NextBytes(6);
            }
        }
Example #3
0
        static void Test6()
        {
            // UDP没有客户端服务器之分。推荐使用NetUri指定服务器地址
            var udp = new UdpServer();

            udp.Remote    = new NetUri("udp://smart.peacemoon.cn:7");
            udp.Received += (s, e) =>
            {
                XTrace.WriteLine("收到:{0}", e.ToStr());
            };
            udp.Open();
            udp.Send("新生命团队");
            udp.Send("学无先后达者为师!");

            // Tcp客户端会话。改用传统方式指定服务器地址
            var tcp = new TcpSession();

            tcp.Remote.Host = "smart.peacemoon.cn";
            tcp.Remote.Port = 13;
            tcp.Open();
            var str = tcp.ReceiveString();

            XTrace.WriteLine(str);

            // 产品级客户端用法。直接根据NetUri创建相应客户端
            var client = new NetUri("tcp://smart.peacemoon.cn:17").CreateRemote();

            client.Received += (s, e) =>
            {
                XTrace.WriteLine("收到:{0}", e.ToStr());
            };
            client.Open();

            Thread.Sleep(1000);
        }
Example #4
0
        static void Test5()
        {
            if (_udpServer != null)
            {
                return;
            }

            _udpServer      = new UdpServer();
            _udpServer.Port = 888;
            //_udpServer.Received += _udpServer_Received;
            _udpServer.SessionTimeout = 5000;
            _udpServer.Open();

            var session = _udpServer.CreateSession(new IPEndPoint(IPAddress.Any, 0));

            for (int i = 0; i < 5; i++)
            {
                var buf = session.Receive();
                Console.WriteLine(buf.ToHex());
                session.Send("Hello");
            }

            //Console.ReadKey();
            _udpServer.Dispose();
            _udpServer = null;
        }
Example #5
0
        /// <summary>开始</summary>
        public void Start()
        {
            if (Client == null)
            {
                Client           = new UdpServer();
                Client.Received += Client_Received;
                Client.Open();

                _Timer = new TimerX(s =>
                {
                    try
                    {
                        SendDiscover();
                    }
                    catch (Exception ex) { WriteLog(ex.ToString()); }
                }, null, 0, 1000);
            }

            //var rnd = new Random();
            TransID = Rand.Next();
            if (_Mac == null || _Mac.Length == 0)
            {
                _Mac = HardInfo.Current.Macs.Replace(":", null).ToHex();
            }
            if (_Mac == null || _Mac.Length == 0)
            {
                _Mac = Rand.NextBytes(6);
            }
        }
Example #6
0
        /// <summary>开始</summary>
        public void Start()
        {
            if (Client == null)
            {
                Client = new UdpServer();
                Client.Received += Client_Received;
                Client.Open();

                _Timer = new TimerX(s =>
                {
                    try
                    {
                        SendDiscover();
                    }
                    catch (Exception ex) { WriteLog(ex.ToString()); }
                }, null, 0, 1000);
            }

            //var rnd = new Random();
            TransID = Rand.Next();
            if (_Mac == null || _Mac.Length == 0)
                _Mac = HardInfo.Current.Macs.Replace(":", null).ToHex();
            if (_Mac == null || _Mac.Length == 0)
                _Mac = Rand.NextBytes(6);
        }
Example #7
0
        private static void Test8()
        {
            XTrace.WriteLine("启动两个服务端");

            // 不管是哪一种服务器用法,都具有相同的数据接收处理事件
            var onReceive = new EventHandler <ReceivedEventArgs>((s, e) =>
            {
                // ReceivedEventArgs中标准使用Data+Length或Stream表示收到的数据,测试时使用ToStr/ToHex直接输出
                // UserState表示来源地址IPEndPoint
                XTrace.WriteLine("收到 {0}:{1}", e.UserState, e.ToStr());

                // 拿到会话,原样发回去。
                // 不管是TCP/UDP,都会有一个唯一的ISocketSession对象表示一个客户端会话
                var session = s as ISocketSession;
                session.Send(e.Stream);
            });

            // 入门级UDP服务器,直接收数据
            var udp = new UdpServer(3388);

            udp.Received += onReceive;
            udp.Open();

            // 入门级TCP服务器,先接收会话连接,然后每个连接再分开接收数据
            var tcp = new TcpServer(3388);

            tcp.NewSession += (s, e) =>
            {
                XTrace.WriteLine("新连接 {0}", e.Session);
                e.Session.Received += onReceive;
            };
            tcp.Start();

            // 轻量级应用服务器(不建议作为产品级使用),同时在TCP/TCPv6/UDP/UDPv6监听指定端口,统一事件接收数据
            var svr = new NetServer();

            svr.Port      = 3377;
            svr.Received += onReceive;
            svr.Start();

            Console.WriteLine();

            // 构造多个客户端连接上面的服务端
            var uri1    = new NetUri(NetType.Udp, IPAddress.Loopback, 3388);
            var uri2    = new NetUri(NetType.Tcp, IPAddress.Loopback, 3388);
            var uri3    = new NetUri(NetType.Tcp, IPAddress.IPv6Loopback, 3377);
            var clients = new ISocketClient[] { uri1.CreateRemote(), uri2.CreateRemote(), uri3.CreateRemote() };

            // 打开每个客户端,如果是TCP,此时连接服务器。
            // 这一步也可以省略,首次收发数据时也会自动打开连接
            // TCP客户端设置AutoReconnect指定断线自动重连次数,默认3次。
            foreach (var item in clients)
            {
                item.Open();
            }

            Thread.Sleep(1000);
            Console.WriteLine();
            XTrace.WriteLine("以下灰色日志为客户端日志,其它颜色为服务端日志,可通过线程ID区分");

            // 循环发送几次数据
            for (int i = 0; i < 3; i++)
            {
                foreach (var item in clients)
                {
                    item.Send("第{0}次{1}发送".F(i + 1, item.Remote.Type));
                    var str = item.ReceiveString();
                    Trace.Assert(!str.IsNullOrEmpty());
                }
                Thread.Sleep(500);
            }

            XTrace.WriteLine("不用担心断开连接等日志,因为离开当前函数后,客户端连接将会被销毁");

            // 为了统一TCP/UDP架构,网络库底层(UdpServer/TcpServer)是重量级封装为ISocketServer
            // 实际产品级项目不关心底层,而是继承中间层(位于NewLife.Net)的NetServer/NetSession,直接操作ISocketSession
            // 平台级项目一般在中间层之上封装消息序列化,转化为消息收发或者RPC调用,无视网络层的存在
            // 以太网接口之上还有一层传输接口ITransport,它定义包括以太网和其它工业网络接口的基本数据收发能力
        }