SignalR服务器>客户端通信无法正常工作 [英] SignalR Server > Client communication not working correct

查看:100
本文介绍了SignalR服务器>客户端通信无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我使用SignalR做了一个聊天应用程序。为了支持一对一聊天,我创建了一个自定义HubPipelineModule,它将SignalR连接添加到以拥有的ProfileID命名的组中。



但是,尽管SignalR连接已正确初始化并且客户端>可以从服务器到客户端进行通信。服务器通信正常工作,但客户端jQuery代码未被调用。我的问题:为什么?



这一切都曾经正常工作但我的移动浏览器一直随机崩溃,所以我决定将所有SignalR / Jquery代码升级到最新版本看看这是否是一个解决方案,但升级后没有服务器>客户沟通工作了。



Global.asax:

  protected   void  Application_Start()
{
// 添加自定义ViewEngine
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add( new CustomRazorViewEngine());

// 添加自定义HubPipeline
GlobalHost.HubPipeline.AddModule ( new CustomHubPipelineModule());

// Map the Hub
RouteTable.Routes.MapHubs ();

AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}





CustomHubPipelineModule.cs:

 使用系统; 
使用 System.Web;
使用 Microsoft.AspNet.SignalR;
使用 Microsoft.AspNet.SignalR.Hubs;
使用 MyChatApp.DataHelpers;

命名空间 MyChatApp
{
public class CustomHubPipelineModule:HubPipelineModule
{
protected 覆盖 bool OnBeforeIncoming(IHubIncomingInvokerContext context)
{
// 用户是否已登录?
if (HttpContext.Current.User!= null
{
// 获取个人资料信息
Profiel_DataHelper profiel =
new Profiel_DataHelper(HttpContext.Current.User.Identity.Name);

// 添加新的连接到ProfielID组
context.Hub.Groups.Add(
context.Hub.Context.ConnectionId,
profiel.ProfielID.ToString());
}

return base .OnBeforeIncoming(context);
}

受保护 覆盖 bool OnBeforeOutgoing(IHubOutgoingInvokerContext context)
{
return base .OnBeforeOutgoing(上下文);
}
}
}





然后我创建了一个服务器端类来与客户交谈。



ChatServer.cs:

 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Web;
使用 Microsoft.AspNet.SignalR;
使用 Microsoft.AspNet.SignalR.Hubs;
使用 MyChatApp.DataHelpers;

/// < 摘要 >
/// 客户端方法(SERVER => CLIENT)
/// < / summary >
public class ChatServer
{
// 给所有用户
public static void addPublicMessage(
字符串 Bericht,
string profielid,
string profielnaam,
string BerichtID,
string DatumActief,
string DatumVerzonden )
{
尝试
{
var context = GlobalHost.ConnectionManager.GetHubContext< ChatHub>();
context.Clients.All.addPublicMessage(
Bericht,profielid.ToString(),
profielnaam,
BerichtID.ToString(),
DatumActief,
DatumVerzonden);
}
catch
{
}
}

// 对特定用户
public < span class =code-keyword> static void addMessage(
string ProfielID,
字符串 Bericht,
?ProfielIDVan,
< span class =code-keyword> long ?ProfielIDNaar,
bool lastmessage,
int openstaan​​deberichten,
DateTime?DatumActief,
bool GelezenDoorOntvanger,
int berichtnr,
long BerichtID,
bool showdate = false
string setdate =
{
try
{
var context = GlobalHost.ConnectionManager.GetHubContext< ChatHub>();
context.Clients.Group(ProfielID).addMessage(
Bericht,
ProfielIDVan.ToString(),
ProfielIDNaar.ToString(),
lastmessage.ToString() ,
openstaan​​deberichten.ToString(),
DatumActief.Value.Hour.ToString( )+ +
DatumActief.Value.Minute.ToString(< span class =code-string> ),
GelezenDoorOntvanger.ToString(),
berichtnr.ToString() ,
BerichtID.ToString(),
showdate.ToString(),
setdate);
}
catch
{
}
}
}





当然还有ClientSide jQuery代码。



Chat.js:

  var  stopevents =  false ; 
var test = null ;
var interval = 1000 ;
var timeout = null ;
var tickercheckdate;

$( function (){

// 客户端:SIGNALR CONNECTION VERLOREN
$ .connection.hub.stateChanged( function (更改){
if (stopevents == false ){
if (change.newState == $ .signalR.connectionState.reconnecting){
timeout = setTimeout( function ( ){
$(' #state')。css(' color'' red'
.html(' 服务器无法访问...');
},interval);
}
其他 if (timeout&& change.newState == = $ .signalR.connectionState.connected){
$(' #state')。 css(' color'' < span class =code-string>')
.html(' ');

clearTimeout(超时);
timeout = null ;
}
}
});

// 客户:SIGNALR CONNECTION START
$ .connection .hub.start()。done( function (){

var chat = $ .connection.Chat;

// SERVER>客户:BERICHT ONTVANGEN VOOR PUBLIEKE CHATBOX
chat.client.addPublicMessage = function (msg,prof_id,prof_naam,bericht_id,bericht_tijd,bericht_datum){
< span class =code-keyword> if
(stopevents == false ){
/ / genereer de chatgeschiedenis met de juiste divs + classes
var bubble = < span class =code-string>' ';

if ($( # ActiveDate)。val()!= bericht_datum){
bubble = bubble + ' < ; center>< div class = \bubble_date \>' + bericht_datum + ' < / DIV>< /中心],[<峰; br />';
$( #ActiveDate)。val(bericht_datum)
}
if (prof_id == 0 ){
bubble = bubble + ' < div class = \bubble_receiver \style = \max-width:' +( $( document )。width() - 70 )+ ' px; \>< div class = \border_receiver \>< / div>< div class = \content_receiver \>' + prof_naam + ' (' + bericht_tijd + ' ):' + msg + ' < / DIV>< / DIV>' ;
}
其他 {
bubble = bubble + ' < div class = \bubble_receiver \style = \max-width:' +($( document )。width() - 70 )+ ' px; \>< div class = \border_receiver \>< / div>< div class = \content_receiver \>< a href = \/ Profielen / Details /' + prof_id + ' \>' + prof_naam + ' < / a> (' + bericht_tijd + ' ):' + msg + ' < / div>< / div>';
}

$(' #publicmessages')。追加(气泡);

jQuery(' html,body')。animate({scrollTop: $( document )。height()}, 1000 );
}
};

// SERVER>客户:BERICHT ONTVANGEN
chat.client.addMessage = 功能(msg,prof,profvan,lastmessage,unreadablemessagecount,datumactief,gelezen,berichtnr, berichtid,showdate,setdate){
if (stopevents == false ){
if (($( #profielid)。val()== prof&& $( #profielidNaar)。 val()== profvan)||($( #profielid)。val()= = profvan&& $( #profielidNaar)。val()== prof)| |(prof == 0 )||(profvan == 0 )){
< span class =code-comment> //
genereer de chatgeschiedenis met de juiste divs + classes

var cssclass = receiver;
if (prof == $( #profielid)。val()){
cssclass = sender;
}
var bubble = ' ;

if (showdate == true ){
bubble = bubble + ' < center>< div class = \bubble_date \>' + setdate + ' < / div>< / center>< br />';
}

bubble = bubble + ' < div class = \ bubble _' + cssclass + ' \style = \max-width:' +($( document )。width() - 70 )+ ' px; \>< div class = \border _' + cssclass + ' \>< / div>< div class = \content _' + cssclass + ' \>' + msg + ' < div class = \tijd _' + cssclass + ' \\ \\>' + datumactief;
if (prof!= $( #profielidNaar)。val()){
bubble = bubble + ' < div class = \gelezen _' + gelezen + ' \id = \read_img' + berichtid + ' \>< / div>';
}
bubble = bubble + ' < / div>< / div>< / DIV>';

$(' #messages')。append(bubble);
}
if (lastmessage == true ){
jQuery (' html,body')。animate({scrollTop:$( document )。height()}, 1000 );
}
}
};
});
});





当然还有标题信息:

 <  !DOCTYPE     html  >  
< html lang = zh >
< ; head >
< title > < / title >

< meta charset = utf-8 / >
< meta name = viewport content = width = device-width / >
< meta 名称 = apple-mobile-web-app-status-bar -style content = black / >
< meta content = width = device-width,initial-scale = 1.0,maximum-scale = 1.0,user-scalable = 0 名称 = viewport / >
< meta 名称 = apple-mobile-web-app-capable content = yes / >

< link href = /Content/jquery.mobile-1.3.0.min.css\" rel = stylesheet / >

< link href = / Files / Styles / Site.css rel = stylesheet type = text / css / >
< link < span class =code-attribute> href = < span class =code-keyword> / Files / Styles / Chat.css rel = 样式表 类型 = text / css / >

< span class =code-keyword>< script src = / Scripts / jQuery / jquery-1.8.3.min.js type = < span class =code-keyword> text / javascript > < / script > ;
< script src = / Scripts / jQuery / jquery.mobile-1.3.0.min.js type = text / javascript > < / script >

< script src = / Scripts / SignalR / jquery.signalR-1.0.1.min.js 类型 = text / javascript < span class =code-keyword>> < / script >
< script src = / signalr / hubs 类型 = text / javascript > ; < / script >

< script src = / Scripts / Website / Chat.js 类型 = text / javascript > < / script >

< / head >

解决方案

< blockquote>( function (){

// 客户端:SIGNALR CONNECTION VERLOREN


.connection.hub.stateChanged( function (更改){
如果(stopevents == false ){
if (change.newState ==


.signalR.connectionState.reconnecting){
timeout = setTimeout( function (){


Hi,

I''ve made a chat application using SignalR. To support 1-on-1 chatting I have created a custom HubPipelineModule that adds the SignalR connections to a group named after the owning ProfileID.

But there is no communication possible from server to client, although the SignalR connection is initialised correctly and the Client > Server communication is working correctly, BUT the clientside jQuery code is not being called. My question: Why?

This all used to work correctly but my mobile browser kept crashing randomly, so I dicided to upgrade all SignalR/Jquery code to the latest version to see if that would be a solution, but after the upgrade no Server > Client communication worked anymore.

Global.asax:

protected void Application_Start()
{
    // Add custom ViewEngine
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new CustomRazorViewEngine());

    // Add custom HubPipeline
    GlobalHost.HubPipeline.AddModule(new CustomHubPipelineModule());

    // Map the Hub
    RouteTable.Routes.MapHubs();

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}



CustomHubPipelineModule.cs:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using MyChatApp.DataHelpers;

namespace MyChatApp
{
    public class CustomHubPipelineModule : HubPipelineModule
    {
        protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context)
        {
            // Is the user logged in?
            if (HttpContext.Current.User != null)
            {
                // Get profile information
                Profiel_DataHelper profiel = 
                    new Profiel_DataHelper(HttpContext.Current.User.Identity.Name);

                // Add new connection to group of the ProfielID
                context.Hub.Groups.Add(
                    context.Hub.Context.ConnectionId, 
                    profiel.ProfielID.ToString());
            }

            return base.OnBeforeIncoming(context);
        }
 
        protected override bool OnBeforeOutgoing(IHubOutgoingInvokerContext context)
        {
            return base.OnBeforeOutgoing(context);
        }
    }
}



Then I have created a serverside class to talk to the clients.

ChatServer.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using MyChatApp.DataHelpers;

/// <summary>
/// Client-side Methods (SERVER => CLIENT)
/// </summary>
public class ChatServer
{
    // To all users
    public static void addPublicMessage(
        string Bericht, 
        string profielid, 
        string profielnaam, 
        string BerichtID, 
        string DatumActief, 
        string DatumVerzonden)
    {
        try
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.addPublicMessage(
                Bericht, profielid.ToString(), 
                profielnaam, 
                BerichtID.ToString(), 
                DatumActief, 
                DatumVerzonden);
        }
        catch
        {
        }
    }

    // To specific user
    public static void addMessage(
        string ProfielID, 
        string Bericht, 
        long? ProfielIDVan, 
        long? ProfielIDNaar, 
        bool lastmessage, 
        int openstaandeberichten, 
        DateTime? DatumActief, 
        bool GelezenDoorOntvanger, 
        int berichtnr, 
        long BerichtID, 
        bool showdate = false, 
        string setdate = "")
    {
        try
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.Group(ProfielID).addMessage(
                Bericht, 
                ProfielIDVan.ToString(), 
                ProfielIDNaar.ToString(), 
                lastmessage.ToString(), 
                openstaandeberichten.ToString(), 
                DatumActief.Value.Hour.ToString("") + ":" +
                DatumActief.Value.Minute.ToString(""), 
                GelezenDoorOntvanger.ToString(), 
                berichtnr.ToString(), 
                BerichtID.ToString(), 
                showdate.ToString(), 
                setdate);
        }
        catch
        {
        }
    }
}



And ofcourse the ClientSide jQuery code.

Chat.js:

var stopevents = false;
var test = null;
var interval = 1000;
var timeout = null;
var tickercheckdate;

$(function () {

    // CLIENT: SIGNALR CONNECTION VERLOREN
    $.connection.hub.stateChanged(function (change) {
        if (stopevents == false) {
            if (change.newState == $.signalR.connectionState.reconnecting) {
                timeout = setTimeout(function () {
                    $('#state').css('color', 'red')
                        .html('The server is unreachable...');
                }, interval);
            }
            else if (timeout && change.newState === $.signalR.connectionState.connected) {
                $('#state').css('color', '')
                        .html('');

                clearTimeout(timeout);
                timeout = null;
            }
        }
    });

    // CLIENT: SIGNALR CONNECTION START
    $.connection.hub.start().done(function () {
    
        var chat = $.connection.Chat;

        // SERVER > CLIENT: BERICHT ONTVANGEN VOOR PUBLIEKE CHATBOX
        chat.client.addPublicMessage = function (msg, prof_id, prof_naam, bericht_id, bericht_tijd, bericht_datum) {
            if (stopevents == false) {
                //genereer de chatgeschiedenis met de juiste divs + classes
                var bubble = '';

                if ($("#ActiveDate").val() != bericht_datum) {
                    bubble = bubble + '<center><div class=\"bubble_date\" >' + bericht_datum + '</div></center><br/>';
                    $("#ActiveDate").val(bericht_datum)
                }
                if (prof_id == 0) {
                    bubble = bubble + '<div class=\"bubble_receiver\" style=\"max-width:' + ($(document).width() - 70) + 'px;\"><div class=\"border_receiver\"></div><div class=\"content_receiver\">' + prof_naam + ' (' + bericht_tijd + '): ' + msg + '</div></div>';
                }
                else {
                    bubble = bubble + '<div class=\"bubble_receiver\" style=\"max-width:' + ($(document).width() - 70) + 'px;\"><div class=\"border_receiver\"></div><div class=\"content_receiver\"><a href=\"/Profielen/Details/' + prof_id + '\">' + prof_naam + '</a> (' + bericht_tijd + '): ' + msg + '</div></div>';
                }

                $('#publicmessages').append(bubble);

                jQuery('html, body').animate({ scrollTop: $(document).height() }, 1000);
            }
        };

        // SERVER > CLIENT: BERICHT ONTVANGEN
        chat.client.addMessage = function (msg, prof, profvan, lastmessage, unreadablemessagecount, datumactief, gelezen, berichtnr, berichtid, showdate, setdate) {
            if (stopevents == false) {
                if (($("#profielid").val() == prof && $("#profielidNaar").val() == profvan) || ($("#profielid").val() == profvan && $("#profielidNaar").val() == prof) || (prof == 0) || (profvan == 0)) {
                    //genereer de chatgeschiedenis met de juiste divs + classes
                    var cssclass = "receiver";
                    if (prof == $("#profielid").val()) {
                        cssclass = "sender";
                    }
                    var bubble = '';

                    if (showdate == true) {
                        bubble = bubble + '<center><div class=\"bubble_date\" >' + setdate + '</div></center><br/>';
                    }

                    bubble = bubble + '<div class=\"bubble_' + cssclass + '\" style=\"max-width:' + ($(document).width() - 70) + 'px;\"><div class=\"border_' + cssclass + '\"></div><div class=\"content_' + cssclass + '\">' + msg + '<div class=\"tijd_' + cssclass + '\">' + datumactief;
                    if (prof != $("#profielidNaar").val()) {
                        bubble = bubble + '<div class=\"gelezen_' + gelezen + '\" id=\"read_img' + berichtid + '\"></div>';
                    }
                    bubble = bubble + '</div></div></div>';

                    $('#messages').append(bubble);
                }
                if (lastmessage == true) {
                    jQuery('html, body').animate({ scrollTop: $(document).height() }, 1000);
                }
            }
        };
    });
}); 



And of course the header information:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
    	<meta name="apple-mobile-web-app-capable" content="yes" />
        
        <link href="/Content/jquery.mobile-1.3.0.min.css" rel="stylesheet" />
        
        <link href="/Files/Styles/Site.css" rel="stylesheet" type="text/css" />
        <link href="/Files/Styles/Chat.css" rel="stylesheet" type="text/css" />
                
        <script src="/Scripts/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
        <script src="/Scripts/jQuery/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
        
        <script src="/Scripts/SignalR/jquery.signalR-1.0.1.min.js" type="text/javascript"></script>
        <script src="/signalr/hubs" type="text/javascript"></script>

        <script src="/Scripts/Website/Chat.js" type="text/javascript"></script>

    </head>

解决方案

(function () { // CLIENT: SIGNALR CONNECTION VERLOREN


.connection.hub.stateChanged(function (change) { if (stopevents == false) { if (change.newState ==


.signalR.connectionState.reconnecting) { timeout = setTimeout(function () {


这篇关于SignalR服务器&gt;客户端通信无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆