/// <summary>
 /// 开启客户端socket
 /// </summary>
 public static void ClientSocketStarting(SocketConnectConfig sktconfig)
 {
     Sktconfig = sktconfig;
     if (ServerSocketEndPoint != null && (SocketClient == null || !SocketClient.Connected))
     {
         SocketClient           = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         SocketClientConnection = new SocketConnectionReConnectClient(SocketClient);
         SocketClient.BeginConnect(ServerSocketEndPoint, ConnectCallback, SocketClientConnection);
     }
 }
        /// <summary>
        /// 开启客户端socket
        /// </summary>
        public static void ClientSocketStarting(Action <ISocketConnection> conncetCallback = null, Action <ISocketConnection> disConnectCallback = null, Action <byte[], ISocketConnection> receiveCallback = null
                                                , Action <ISocketConnection> sendCallback  = null, Action <string> showMsg = null, Action <Exception> socketExceptionCallback = null)
        {
            SocketConnectConfig sktconfig = new SocketConnectConfig()
            {
                ConnectCallback                = conncetCallback,
                DisConnectCallback             = disConnectCallback,
                ReceiveCallback                = receiveCallback,
                SendCallback                   = sendCallback,
                ShowMsg                        = showMsg,
                SocketConnectExceptionCallback = socketExceptionCallback
            };

            ClientSocketStarting(sktconfig);
        }
示例#3
0
        /// <summary>
        /// 开启服务端socket监听
        /// </summary>
        public static void ServerSocketRefListing(Action <ISocketConnection> acceptCallback            = null, Action <ISocketConnection> disConnectCallback = null
                                                  , Action <byte[], ISocketConnection> recevieCallBack = null, Action <ISocketConnection> sendCallback       = null
                                                  , Action <string> showMsg = null, Action <Exception> socketExceptionCallback = null, Action disposeCallback = null)
        {
            var sktconfig = new SocketConnectConfig()
            {
                AcceptCallback                 = acceptCallback,
                DisConnectCallback             = disConnectCallback,
                ReceiveCallback                = recevieCallBack,
                SendCallback                   = sendCallback,
                ServerSocket                   = ServerSocketListenner,
                ShowMsg                        = showMsg,
                SocketConnectExceptionCallback = socketExceptionCallback,
                DisposeCallback                = disposeCallback
            };

            ServerSocketRefListing(sktconfig);
        }
        /// <summary>
        /// 开启服务端socket监听
        /// </summary>
        public static void ServerSocketListing(SocketConnectConfig sktconfig)
        {
            DicSockectConnection.Clear();
            _cancellationTocken = new CancellationTokenSource();
            if (sktconfig == null)
            {
                sktconfig = new SocketConnectConfig()
                {
                    ServerSocket = ServerSocketListenner
                }
            }
            ;
            else if (sktconfig.ServerSocket == null)
            {
                sktconfig.ServerSocket = ServerSocketListenner;
            }
            Sktconfig = sktconfig;
            try
            {
                if (SocketConnectionClient.SocketClient != null && SocketConnectionClient.SocketClient.Connected)
                {
                    SocketConnectionClient.SocketClientConnection.Disconnect();
                }

                SocketConnectionClient.ClientSocketStarting(connection =>
                {
                    ServerSocketClient = (SocketConnection)connection;
                    SendCurrentConnectionCount();
                }     //监听打开后,发送当前上位机的连接数目信息
                                                            );

                ServerSocketListenner.IOControl(IOControlCode.KeepAliveValues, KeepAlive(1, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000), null); //设置心跳检测
                ServerSocketListenner.BeginAccept(AcceptCallback, sktconfig);
                Task.Run(() =>                                                                                                                                                          //解决主线程直接调用报错
                {
                    ShowMsg($"socket server listening at {ServerSocketListenner.LocalEndPoint}...");
                });
            }
            catch (SocketException se)
            {
                SocketException(ServerSocketListenner, se);
            }
        }
示例#5
0
        /// <summary>
        /// 开启服务端socket监听
        /// </summary>
        public static void ServerSocketRefListing(SocketConnectConfig sktconfig)
        {
            var pfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*Process.dll");

            foreach (var fileName in pfiles)
            {
                var assembly = Assembly.LoadFile(fileName);
                var types    = assembly.GetTypes().Where(e => e.GetInterfaces().Any(e1 => e1.Namespace != null && e1.Namespace.Equals("Socket.Reflect") && e1.Name.Equals("IProcess`1")));//IProcess`1
                foreach (var type in types)
                {
                    type.GetCustomAttributes().ToList().ForEach(e =>
                    {
                        var code = e as CmdCodeAttribute;
                        if (code != null && type.GetInterfaces().Length > 0)
                        {
                            ReflactProcesses.Add(code.CmdCode, new ProcessRef()
                            {
                                ProcessType = type, RefObj = Activator.CreateInstance(type), ArgType = type.GetInterfaces()[0].GetGenericArguments()[0]
                            });
                        }
                    });
                }
            }
            var sktconfig2 = new SocketConnectConfig
            {
                AcceptCallback     = sktconfig.AcceptCallback,
                BeforeSend         = sktconfig.BeforeSend,
                ConnectCallback    = sktconfig.ConnectCallback,
                DisConnectCallback = (con) =>
                {
                    sktconfig.DisConnectCallback(con);
                    if (con.SocketConnectType == SocketConnectType.DeviceSocket)
                    {
                        //var appconfig = CommCode.AppSettings("gettuiappid", "gettuiappkey", "gettuimasterkey");
                        //if (con.StateData.BoundList == null) return;
                        //foreach (var usrClient in con.StateData.BoundList)
                        //{
                        //    CommCode.GeTuiMsg("设备通知", "设备" + con.Identity + "离线", appconfig[0], appconfig[1], appconfig[2], usrClient.ClientId, null);
                        //}
                        ClientRequest.DeviceOffLine(new DtoOffLine
                        {
                            ImeiNo           = con.Identity,
                            RemoteIpEndPoint = con.ConnectSocket.RemoteEndPoint.ToString(),
                            ServerIp         = con.ConnectSocket.LocalEndPoint.ToString()
                        });
                    }
                },
                DisposeCallback = sktconfig.DisposeCallback,
                KeepAliveTime   = sktconfig.KeepAliveTime,
                SendCallback    = sktconfig.SendCallback,
                ShowMsg         = sktconfig.ShowMsg,
                ReceiveCallback = (bytes, con) =>
                {
                    sktconfig.ReceiveCallback?.Invoke(bytes, con); //先执行外面注册展示层的方法

                    var header = CmdHeader.Parser.ParseFrom(bytes);
                    if (string.IsNullOrWhiteSpace(header.Identity))
                    {
                        return;
                    }
                    #region 反射执行Process
                    SocketConnection oppSocketConnection;
                    if (ReflactProcesses.Keys.Contains(header.CmdCode))
                    {
                        var objProcess = ReflactProcesses[header.CmdCode];
                        var param      = objProcess.ArgType.Name.Equals("CmdHeader")
                            ? header
                            : objProcess?.ArgType.GetProperty("Parser")?
                                         .PropertyType.GetMethod("ParseFrom", new[] { typeof(byte[]) })?
                                         .Invoke(objProcess.ArgType.GetProperty("Parser")?.GetValue(objProcess.RefObj),
                                                 new object[] { bytes });
                        if (param == null)
                        {
                            return;
                        }
                        try
                        {
                            objProcess?.ProcessType.InvokeMember("ProcessReqest",
                                                                 BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null,
                                                                 objProcess.RefObj, new[] { param, con, ClientRequest });
                        }
                        catch (Exception ex)
                        {
                            ShowMsg($"{DateTime.Now:yyyy/MM/dd HH:mm:ss.fffffff} 调用发生异常{(ex.InnerException != null ? ex.InnerException.StackTrace : ex.StackTrace)}");
                        }
                    }
                    else if (string.IsNullOrWhiteSpace(header.OppositeId)) //没有操作对象,不需要上位机处理
                    {
                        var msgBk = new CmdHeader
                        {
                            CmdCode    = header.CmdCode,
                            Identity   = header.Identity,
                            ResultCode = 1,
                            ServerId   = ServerId,
                            //TimeToken = header.TimeToken
                        };
                        con.Send(msgBk.ToByteArray());
                    }
                    else if (DicSockectConnection.TryGetValue(header.OppositeId,
                                                              out oppSocketConnection))
                    {
                        ShowMsg($"{DateTime.Now:yyyy/MM/dd HH:mm:ss.fffffff} 透传控制查询:{header.OppositeId}");
                        oppSocketConnection.Send(bytes);
                    }
                    else //设备离线
                    {
                        var msgBk = new CmdHeader
                        {
                            CmdCode    = header.CmdCode,
                            Identity   = header.Identity,
                            OppositeId = header.OppositeId,
                            ResultCode = 3, //离线
                            ServerId   = ServerId,
                            //TimeToken = header.TimeToken
                        };
                        con.Send(msgBk.ToByteArray());
                        if (con.SocketConnectType == SocketConnectType.DeviceSocket)
                        {
                            ClientRequest.DeviceOffLine(new DtoOffLine
                            {
                                ImeiNo           = header.OppositeId,
                                RemoteIpEndPoint = "",
                                ServerIp         = ""
                            });
                        }
                    }

                    #endregion
                }
            };

            ServerSocketListing(sktconfig2);
        }