/// <summary>
        /// 向指定用户发送消息
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="userid"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task SendMessageToUser(ICustomWebSocketFactory factory, string userid, Object data)
        {
            var user = factory.Client(userid);

            if (user != null)
            {
                string serialisedMessage = JsonConvert.SerializeObject(data);
                byte[] bytes             = Encoding.UTF8.GetBytes(serialisedMessage);
                await user.WebSocket.SendAsync(new ArraySegment <byte>(bytes, 0, bytes.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 发送消息给指定的客户端
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task SendMessageToSingle(string msg, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            var    client = wsFactory.Client(userWebSocket);

            if (client != null)
            {
                if (client.WebSocket.State != WebSocketState.Open)
                {
                    Log4netHelper.Info(this, "此websocket的状态为:" + client.Username + "<>" + client.WebSocket.State.ToString());
                    return;
                }
                await client.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }