예제 #1
0
        /// <summary>
        /// 以送信息给所有客户端
        /// </summary>
        /// <param name="msg"></param>
        public void SendMsgToAllClient(string msg)
        {
            lockSlim.EnterReadLock();

            try
            {
                foreach (var item in dictsocket)
                {
                    if (SocketTools.IsSocketConnected(item.Value.socket))
                    {
                        item.Value.socket.Send(SocketTools.GetBytes(msg, IsOpenDesEnc));
                    }
                    else
                    {
                        item.Value.socket.Close();

                        OnDebug?.Invoke($"The client with ip {item.Key} has logged out and can't send a message.");
                    }
                }
            }
            catch (Exception ex)
            {
                OnError?.Invoke($"Error when sending to all clients:{ex.ToString()}");
            }
            finally
            {
                lockSlim.ExitReadLock();
            }
        }
예제 #2
0
        /// <summary>
        /// 通过ip发送信息给客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="msg"></param>
        public bool SendMsgToClientForIP(string ip, string msg)
        {
            lockSlim.EnterReadLock();

            bool isok = true;

            try
            {
                if (dictsocket.ContainsKey(ip.Trim()))
                {
                    ClientMode clientMode = dictsocket[ip.Trim()];
                    if (SocketTools.IsSocketConnected(clientMode.socket))
                    {
                        clientMode.socket.Send(SocketTools.GetBytes(msg, IsOpenDesEnc));
                        isok = true;
                    }
                    else
                    {
                        clientMode.socket.Close();

                        OnDebug?.Invoke($"The client with ip {clientMode.ip} has logged out and can't send a message.");
                        isok = false;
                    }
                }
            }
            catch (Exception ex)
            {
                OnError?.Invoke($"Error when sending to the client:{ex.ToString()}");
                isok = false;
            }
            finally
            {
                lockSlim.ExitReadLock();
            }

            return(isok);
        }