首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebSocket实现

WebSocket实现
EN

Stack Overflow用户
提问于 2016-02-03 14:21:13
回答 2查看 953关注 0票数 0

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

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

E.g

ClientSide实现

代码语言:javascript
复制
 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
   }

服务器端实现

代码语言:javascript
复制
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的方式正确吗?

请帮我在这一部分清空。

EN

回答 2

Stack Overflow用户

发布于 2016-02-03 18:27:55

这里有一个示例。

首先,您必须安装Asp.net SignalR包及其依赖项。

当应用程序启动时,您必须调用SignalR

代码语言:javascript
复制
namespace ABC
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR(); <--{Add this line}
        }        
    }
}

Global.asax文件中,您必须在应用程序启动时启动SqlDependency,当应用程序停止时停止。

代码语言:javascript
复制
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringsName"].ConnectionString;
        protected void Application_Start()
        {
            SqlDependency.Start(ConnectionString);
        }
        protected void Application_End()
        {
            SqlDependency.Stop(ConnectionString);
        }

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

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

然后在客户机页中,将这些代码添加到javascript部分

代码语言: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',
               .
               .
       }

当使用sqlDependencydatabase table中有任何更改时,服务器将调用此函数

getAllMessages()是要处理的代码的控制器,它应该显示在视图页面中,当应用程序启动和数据库中的任何更改时都会调用它。

代码语言:javascript
复制
public ActionResult GetNotificationMessages()
        {
            NotificationRepository notification = new NotificationRepository();
            return PartialView("_NotificationMessage");
        }

in model

代码语言:javascript
复制
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更新时显示最新数据。消息将在运行时显示。

希望这能有所帮助

票数 0
EN

Stack Overflow用户

发布于 2016-02-17 21:28:41

你走在正确的道路上

如果我没有迟到,你可以参考这个...This正在工作的例子

客户端

代码语言:javascript
复制
    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>
代码语言:javascript
复制
<div id="log">

</div>

Websocketserver.ashx页面中的服务器端

公共类WebSocketsServer : IHttpHandler {

代码语言:javascript
复制
    public void ProcessRequest(HttpContext context)
    {
        if (context.IsWebSocketRequest)
        {
            context.AcceptWebSocketRequest(new MicrosoftWebSockets());
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

在服务器端添加下面的类

代码语言:javascript
复制
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));
    }

使用Microsoft.Web.WebSockets将这个dll添加到上面的类中;

我不记得我从哪里得到的参考...but上面的代码是从我当前工作的应用程序派生而来的

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35169860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档