コード例 #1
0
        /// <summary>
        /// 发送消息给指定的客户端(用户名相同的所有客户端)
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="username"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task SendMessage(string msg, string username, ICustomWebSocketFactory wsFactory)
        {
            var clients = wsFactory.Clients(username);

            if (clients != null)
            {
                foreach (var client in clients)
                {
                    if (client.WebSocket.State != WebSocketState.Open)
                    {
                        Log4netHelper.Info(this, "此websocket的状态为:" + client.Username + "<>" + client.WebSocket.State.ToString());
                        continue;
                    }
                    byte[] buffer = Encoding.UTF8.GetBytes(msg);
                    await client.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);

                    //Log4netHelper.Info(this, client.Username + "-->推送消息成功:" + msg);
                }
            }
            else
            {
                Log4netHelper.Info(this, username + "-->客户端不存在!");
            }
        }