WebSocket实施

时间:2016-02-03 06:21:13

标签: c# asp.net api websocket

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

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

E.g

ClientSide实施

 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?

请帮我详细说明。

2 个答案:

答案 0 :(得分:0)

这是一个样本。
首先,您必须安装Asp.net SignalR包及其依赖项 你在应用程序启动时调用SignalR

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

您在应用开始时启动SqlDependency,当应用停在Global.asax文件中时停止。

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 tablesqlDependency发生任何变化时,服务器会调用此函数 getAllMessages()是您的代码要处理的控制器,应该显示在视图页面中,当应用程序启动时将调用它并且db中的任何更改

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

in model class

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更新时显示最新数据。消息将在运行时显示 希望这有帮助

答案 1 :(得分:0)

你走在正确的道路上

如果我不迟到,你可以参考这个......这是一个有效的例子

客户端  

    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页面中的服务器端

public class 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;

我不记得我获得参考的地方......但上面的代码来自我当前的工作申请