Реагировать на собственный signalr ASP. net WebApi 2 (SignalR: Fired ajax abort asyn c = true.) - PullRequest
0 голосов
/ 06 мая 2020

Я использую Signalr (react-native-signalr V1.0.6) с React-native на некоторых мобильных устройствах (Android), я получаю журнал ниже, и код не работает.
Пожалуйста, помогите мне, я не знаю, почему не работает в некоторых Android ОС.

Это мои зависимости:

dependencies: {
...
    "react": "16.11.0",
    "react-native": "0.62.2",
    "react-native-signalr": "^1.0.6",
...
}

Это файл ajax. js в пакете:

const qs = data => {
  let results = [];
  for (const name in data)
    results.push(`${name}=${encodeURIComponent(data[name])}`);
  return results.join('&');
};
export default (headers, options) => {
  const request = new XMLHttpRequest();
  let aborted = false;
  request.onreadystatechange = () => {
    if (request.readyState !== 4 || aborted) {
      return;
    }
    if (request.status === 200 && !request._hasError && options.success) {
      try {
        options.success(JSON.parse(request.responseText));
      } catch (e) {
        options.error(request, e);
      }
    } else if (options.error) {
      options.error(request, request._response);
    }
  };
  request.open(options.type, options.url);
  request.setRequestHeader('content-type', options.contentType);
  if (options.xhrFields) {
    Object.keys(options.xhrFields).forEach(key => {
      const value = options.xhrFields[key];
      request[key] = value;
    });
  }
  if (headers) {
    Object.keys(headers).forEach(key => {
      const value = headers[key];
      request.setRequestHeader(key, value);
    });
  }
  request.send(
    options.type === 'POST' ? options.data && qs(options.data) : undefined,
  );
  return {
    abort: reason => {
      aborted = true;
      return request.abort(reason);
    },
  };
};

Это индекс. js пакета:

let signalRHubConnectionFunc;
const makeSureDocument = () => {
  const originalDocument = window.document;
  window.document = window.document || { readyState: "complete" };
  if (!window.document.readyState) {
    window.document.readyState = "complete";
  }
  return () => (window.document = originalDocument);
};
if (!window.addEventListener) {
  window.addEventListener = window.addEventListener = () => {};
}
window.navigator.userAgent = window.navigator.userAgent || "react-native";
window.jQuery = require("./signalr-jquery-polyfill.js").default;
export default {
  setLogger: logger => {
    if (window.console && window.console.debug) {
      window.console.debug("OVERWRITING CONSOLE.DEBUG in react-native-signalr");
    } else if (!window.console) {
      window.console = {};
    }
    const originalDebug = window.console.debug;
    window.console.debug = logger;
    return () => (window.console.debug = originalDebug);
  },
  hubConnection: (serverUrl, options) => {
    const revertDocument = makeSureDocument();
    if (!signalRHubConnectionFunc) {
      require("ms-signalr-client");
      signalRHubConnectionFunc = window.jQuery.hubConnection;
    }
    const [protocol, host] = serverUrl.split(/\/\/|\//);
    if (options && options.headers) {
      window.jQuery.defaultAjaxHeaders = options.headers;
    }
    const hubConnectionFunc = signalRHubConnectionFunc(serverUrl, options);
    const originalStart = hubConnectionFunc.start;
    revertDocument();
    hubConnectionFunc.start = (options, ...args) => {
      const revertDocument = makeSureDocument();
      window.document.createElement = () => {
        return {
          protocol,
          host,
        };
      };
      window.location = {
        protocol,
        host,
      };
      const returnValue = originalStart.call(hubConnectionFunc, options, ...args);
      revertDocument();
      return returnValue;
    };
    return hubConnectionFunc;
  },
};

и это мой компонент для получения данных в реальном времени:

import signalr from 'react-native-signalr';
import { baseUrl2 } from '../services/ReqServices';
import {
  AsyncStorage
} from 'react-native';
const SRBIItem = async (setItems) => {
  // this.setState({ loading: true })
  let dir = []
  let token = await AsyncStorage.getItem('UserToken');
  //This is the server under /example/server published on azure.
  const connection = signalr.hubConnection(baseUrl2);
  connection.logging = true;
  const proxy = connection.createHubProxy('chatHub');
  //receives broadcast messages from a hub function, called "helloApp"
  proxy.on('helloApp', (arg) => {
    console.log(JSON.stringify(arg));
    setItems(arg)
    //Here I could response by calling something else on the server...
  });
  // atempt connection, and handle errors
  connection.start({withCredentials:true, transport: ['webSockets']}).done(() => {
    console.log('Now connected, connection ID=' + connection.id);
    proxy.invoke('getNewOrders', connection.id, token)
      .done((directResponse) => {
        dir = directResponse;
        // setItems(directResponse)
        // console.log('my connection id:', JSON.stringify(directResponse));
        // return directResponse
        // this.setState({ data: directResponse, loading: false })
      }).fail(() => {
        console.warn('Something went wrong when calling server, it might not be up and running?')
      });
  }).fail(() => {
    console.log('Failed');
  });
  //connection-handling
  connection.connectionSlow(() => {
    console.log('We are currently experiencing difficulties with the connection.')
  });
  connection.error((error) => {
    const errorMessage = error.message;
    let detailedError = '';
    if (error.source && error.source._response) {
      detailedError = error.source._response;
    }
    if (detailedError === 'An SSL error has occurred and a secure connection to the server cannot be made.') {
      console.log('When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14')
    }
    console.debug('SignalR error: ' + errorMessage, detailedError)
  });
}
export default SRBIItem;

и это файл chathub.cs на стороне сервера (файл концентратора):

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using WebApplication.Models;
namespace WebApplication.Hubs
{
    public class chatHub : Hub
    {
        public static void notifyUserToAllClients()
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<chatHub>();
            context.Clients.All.updatedClients();
        }
        public List<ListRequestViewModels> getNewOrders(string connection, string token)
        {
            using (DataBaseContext db = new DataBaseContext())
            {
                List<string> Connections = new List<string>();
                List<ListRequestViewModels> list = new List<ListRequestViewModels>();
                var service = db.Servicess.FirstOrDefault(t => t.Token == token);
                var user =db.UserConnectionIds.FirstOrDefault(t =>t.Services.Token == token);
                if (user != null)
                {
                    user.UserConnection = connection;
                    db.SaveChanges();
                }
                else
                {
                    if (service != null)
                        db.UserConnectionIds.Add(new UserConnectionId()
                        {
                            ServiceId = service.ServiceId,
                            UserConnection = connection
                        });
                    db.SaveChanges();
                    Connections.Add(connection);
                }
                var allconnection = db.UserConnectionIds.Where(t => t.Services.Token == token).ToList();
                Connections.AddRange(allconnection.Select(item => item.UserConnection));
                var requests = db.Finalies.Where(t => t.RestaurantId == service.ServiceId && t.Status != 3).ToList();
                list.AddRange(requests.Select(item => new ListRequestViewModels()
                {
                    Phone = item.User.Phone,
                    Address = item.Address,
                    Hour = item.HourDate,
                    Price = item.SumPrice,
                    RequestId = item.id,
                    Status = item.Status.Value
                }));
                Clients.Caller.helloApp(list);
                Connections.Add(connection);
                return list;
            }
        }
        public void getNewOrdersAfterOrder(string connection, string token)
        {
            using (DataBaseContext db = new DataBaseContext())
            {
                List<string> Connections = new List<string>();
                List<ListRequestViewModels> list = new List<ListRequestViewModels>();
                var service = db.Servicess.FirstOrDefault(t => t.Token == token);
                var user = db.UserConnectionIds.FirstOrDefault(t => t.Services.Token == token);
                if (user != null)
                {
                    user.UserConnection = connection;
                    db.SaveChanges();
                }
                else
                {
                    if (service != null)
                        db.UserConnectionIds.Add(new UserConnectionId()
                        {
                            ServiceId = service.ServiceId,
                            UserConnection = connection
                        });
                    db.SaveChanges();
                    Connections.Add(connection);
                }
                var requests = db.Finalies.Where(t => t.RestaurantId == service.ServiceId && t.Status != 3).ToList();
                list.AddRange(requests.Select(item => new ListRequestViewModels()
                {
                    Phone = item.User.Phone,
                    Address = item.Address,
                    Hour = item.HourDate,
                    Price = item.SumPrice,
                    RequestId = item.id,
                    Status = item.Status.Value
                }));
                Connections.Add(connection);
                Clients.Client(connection).helloApp(list);
            }
        }
    }
}

Я запускаю свой проект, использую реактивный запуск- android на некоторых Android мобильных устройствах, он не работает, и я получаю журнал ниже:


[Tue May 05 2020 00:17:33.493]  LOG      Running "hamemarket_markets" with {"rootTag":81}
[Tue May 05 2020 00:17:36.195]  DEBUG    [00:17:34 GMT+0430 (+0430)] SignalR: Client subscribed to hub 'chathub'.
[Tue May 05 2020 00:17:36.236]  DEBUG    [00:17:34 GMT+0430 (+0430)] SignalR: Negotiating with 'http://hamemarket.ir/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D'.
[Tue May 05 2020 00:17:37.108]  DEBUG    [00:17:35 GMT+0430 (+0430)] SignalR: webSockets transport starting.
[Tue May 05 2020 00:17:37.114]  DEBUG    [00:17:35 GMT+0430 (+0430)] SignalR: Connecting to websocket endpoint 'ws://hamemarket.ir/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=heF9BdlhdTlykyzw9r%2FI1vkS%2BUx1yOSKDrBAZkfxMzwUUxoPJda0q5QouZCj0oRRcRYuoq3F%2FwNArBNejq1f%2FtJPkrdSVfXSJVMjNlvX1EvppzlKdVOTtFKfqjBGXU6i&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&tid=8'.
[Tue May 05 2020 00:17:37.451]  DEBUG    [00:17:35 GMT+0430 (+0430)] SignalR: Websocket opened.
[Tue May 05 2020 00:17:42.136]  DEBUG    [00:17:40 GMT+0430 (+0430)] SignalR: webSockets transport timed out when trying to connect.
[Tue May 05 2020 00:17:42.145]  DEBUG    [00:17:40 GMT+0430 (+0430)] SignalR: Closing the Websocket.
[Tue May 05 2020 00:17:42.147]  DEBUG    [00:17:40 GMT+0430 (+0430)] SignalR: webSockets transport failed to connect. Attempting to fall back.
[Tue May 05 2020 00:17:42.150]  DEBUG    [00:17:40 GMT+0430 (+0430)] SignalR: No fallback transports were selected.
[Tue May 05 2020 00:17:42.152]  DEBUG    SignalR error: No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.
[Tue May 05 2020 00:17:42.156]  LOG      Failed
[Tue May 05 2020 00:17:42.169]  DEBUG    [00:17:40 GMT+0430 (+0430)] SignalR: Stopping connection.
[Tue May 05 2020 00:17:42.198]  DEBUG    [00:17:40 GMT+0430 (+0430)] SignalR: Fired ajax abort async = true.



Что это за SignalR: Сработал ajax abort asyn c = true. , и как это исправить? Благодарим за терпение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...