WebSocket Implementation



我想创建 WebSocket 示例,其中我不想刷新页面以获取最新数据。

我创建了一个 Html 页面,在其中创建一个 websocket 对象。

例如

客户端实现

 var ws = new WebSocket(hostURL);
 ws.onopen = function ()
      {
                // When Connection Open
      };
ws.onmessage = function (evt) 
     {
        // When Any Response come from WebSocket
     }
 ws.onclose = function (e) 
   { 
       // OnClose of WebSocket Conection
   }

服务器端实现

public class WebSocketManager : WebSocketHandler
{
     private static WebSocketCollection WebSocketObj4AddMessage = new WebSocketCollection();
    public override void OnOpen()
    {
      // Do when Connection Is Open
    }
    public override void OnClose()
    {
       // Close Connection
    }
    public override void OnMessage(string message)
    {
        // When Any Message Sent to Client
    }
}

我使用WebSocket的方式是否正确?

请帮助我在本节中清除。

这里有一个示例。
首先,您必须安装Asp.net SignalR包及其依赖项。
你已在应用启动时调用 SignalR

namespace ABC
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR(); <--{Add this line}
        }        
    }
}

Global.asax文件中,应用启动时启动SqlDependency,应用停止时停止。

string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringsName"].ConnectionString;
        protected void Application_Start()
        {
            SqlDependency.Start(ConnectionString);
        }
        protected void Application_End()
        {
            SqlDependency.Stop(ConnectionString);
        }

您必须创建自定义Hubclass扩展Hub Base class

public class MessagesHub : Hub
{
    [HubMethodName("sendMessages")]
    public void SendMessages()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
        context.Clients.All.updateMessages();
    }
}

然后在客户端页面中,在javascript部分添加了这些代码

   $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.messagesHub;
        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
            getAllMessages()
        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });
    function getAllMessages() {
            $.ajax({
               url: '../../Notifications/GetNotificationMessages',
               .
               .
       }

database table有任何更改时,服务器使用 sqlDependency
调用此函数getAllMessages()是代码要处理的控制器,应显示在视图页面中,当应用程序启动和数据库
发生任何更改时将调用它

public ActionResult GetNotificationMessages()
        {
            NotificationRepository notification = new NotificationRepository();
            return PartialView("_NotificationMessage");
        }

model

public class NotificationRepository
    {
        readonly string connectionString = ConfigurationManager.ConnectionStrings["InexDbContext"].ConnectionString;
        public IEnumerable<Notification> GetAllMessages(string userId)
        {
            var messages = new List<Notification>();
            using(var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [NotificationID], [Message], [NotificationDate], [Active], [Url], [userId] FROM [dbo].[Notifications] WHERE [Active] = 1 AND [userId] ='" + userId + "'", connection))
                {
                    command.Notification = null;
                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    if (connection.State == ConnectionState.Closed)
                    {
                        connection.Open();
                    }
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        messages.Add(item: new Notification { NotificationID = (int)reader["NotificationID"], Message = (string)reader["Message"], Url = (string)reader["Url"] });
                    }
                }
            }
            return messages;
        }
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub message = new MessagesHub();
                message.SendMessages();
            }
        }
    }

这很好地显示了database table更新时的最新数据。 该消息将在运行时显示。
希望这有帮助

你走在正确的道路上

如果我不迟到,你可以参考这个...这是工作示例

客户端

    var ws;
    var username = "JOHN";
    function startchat() {
        var log= $('log');
        var url = 'ws://<server path>/WebSocketsServer.ashx?username=' + username;
        ws = new WebSocket(url);
        ws.onerror = function (e) {
            log.appendChild(createSpan('Problem with connection: ' + e.message));
        };
        ws.onopen = function () {
            ws.send("I am Active-" +username);
        };
        ws.onmessage = function (e) {

            if (e.data.toString() == "Active?") {
                ws.send("I am Active-" + username);
            }
            else {
            }
        };
        ws.onclose = function () {
            log.innerHTML = 'Closed connection!';
        };
    }
</script>

<div id="log">
</div>

Websocketserver.ashx 页面中的服务器端

公共类 WebSocketsServer : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        if (context.IsWebSocketRequest)
        {
            context.AcceptWebSocketRequest(new MicrosoftWebSockets());
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

在服务器端添加下面的类

public class MicrosoftWebSockets : WebSocketHandler
{
    private static WebSocketCollection clients = new WebSocketCollection();
    private string msg;
    public override void OnOpen()
    {
        this.msg = this.WebSocketContext.QueryString["username"];
        clients.Add(this);
        clients.Broadcast(msg);
    }
    public override void OnMessage(string message)
    {
        clients.Broadcast(string.Format(message));
    }
    public override void OnClose()
    {
        clients.Remove(this);
        clients.Broadcast(string.Format(msg));
    }

将此 DLL 添加到上述类 使用 Microsoft.Web.WebSockets;

我不记得我从哪里得到参考...但上面的代码来自我当前的工作应用程序

相关内容

  • 没有找到相关文章

最新更新