ChatScreen.js
import React, { Component } from 'react';
import { StyleSheet, View, Text, AsyncStorage, Platform, KeyboardAvoidingView, SafeAreaView } from 'react-native';
import { Header } from 'react-navigation-stack';
import { GiftedChat } from 'react-native-gifted-chat';
import Constants from 'expo-constants';
import moment from 'moment';
import * as signalR from '@aspnet/signalr';
export default class ChatScreen extends Component {
constructor(props) {
super(props);
}
state = {
username: '',
seq: '',
messages: [{
_id: 1,
text: 'Hello developer',
createdAt: moment.utc().format("YYYY/MM/DD HH:mm:ss").toString(),//new Date(),
user: {
_id: 2,
name: 'React',
avatar: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAYAAAAehFoBAAAJhklEQVR4Ab2XA5gky7ZG1x+RmYXW2Lpjz7Nt27Zt27Zt2/a7PjZGR90z0y51ZcS+WZkHo66uvgfr65X4EPHXrt27owUvnisf8q9HTTqJcUhwANgMIHEtRi4gHhN2P/AwLxIVm/HmENGHqRDs3UGHwagQ1yPAsOeeHgX9J8ZfQem60cwH/zvrQf3kc62WfzWmY7wIBA9Z3/8o8MvrC/z+/80oWGIfj+y7wY4AYOJFIQPA0KMyfQvwh4xAYokxjEiUcL8h+DQMDMcwlIhwdQXM8FtqWDBuiwkAYYeBPzD4YLP46YANDRwtshohhFd55/8WpxMGgBiKE2F2hfTUFCRi5e5F/MYUorEahqjgUzG9TQj5hwCPrxo45IHb0dy772jr4sXX4ZNJY0T6RlyB8U/Zj5tKufpldxF7hlIxEvInLPbvGNt/4G2AR24buLl3PzeTz7b39WZmXu/T+oTJMSpxvkd2dgN+XxM5kZ2ZovuaWfy2OiMh8Gltsjcz/QafTJwBLt4SuAjHzfRa8//rvJ+QTzAzRkGC0DbS01P4DSmxE0mOT2L/OwcSZqMWOSXmYSLvzf8PsPeWwEU4rkdJ9qcuTfeAsAggRiEGw01kZOemsGCwEslOTOA21ogrhhLHKJgBzuOc22OmPwc+kutwRUBesP6xMn2UmcNMGKMb5gPJ4XFqpyaIrYD1IumhMZKDY4T5i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HixhxhCa78WZfp3+uwdEdO42CKEmG5sRYWwI+L+kHH7D+t0H4ksP0TG/QXq7VBAFhE4PCu/z6+5ma5Cd35PjPcjqktzfeffrL3D1ndASBfzdDe05F0g0g2OQhgrA8BeAiLRn82km1zuKawQMlKN7J9d+0DgH/kNuj8JyyzGtNP9d4nydxfOGmMVwCL1ur340cA/8IqJEUohvAvmJ0y+T8CezteVvRaU/6xSaZLDMElmRgm4qJZ/vag7zApN8RLbA76duDtpeRSIUN9w/suMirO/B4L+uo8DV/qDM+LwLDog/9JiR8DnmBEdMd7t1g3OXvymn0SxocB7wg4RiMArxb6q6TH7wOXWSe6891avBj6dXYReUuMM0ivArYCE1QsGVyR2Xkc9yDuAJ7iRfAmHf/gI2GxdiAAAAAASUVORK5CYII=',
},
}],
signalRConnection: null
};
static navigationOptions = ({ navigation }) => ({
title: (navigation.state.params || {}).key || 'NULL!',
headerForceInset: { vertical: 'never' }
});
_bootstrap = async () => {
const username = await AsyncStorage.getItem('username');
this.setState({ name: username });
}
componentDidMount = () => {
console.log("componentDidMount");
let connection = new signalR.HubConnectionBuilder()
.withUrl("http://192.168.111.14:5000/api/chat", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.configureLogging(signalR.LogLevel.Debug)
.build();
console.log('what is connection?')
console.log(connection)
connection
.start()
.then(() => console.log('Connection started'))
.catch(err => console.log('Error while starting connection: ' + err));
}
onSend(message = []) {
sendMessage = () => {
this.state.hubConnection
.invoke('sendToAll', this.state.nick, this.state.message)
.catch(err => console.error(err));
}
}
render()
const mainContent = (
<GiftedChat
messages={this.state.messages}
onSend={(messages) => this.onSend(messages)}
user={{ _id: 1 }}
/>
);
if (Platform.OS === 'android') {
return (
<KeyboardAvoidingView style={{ flex: 1 }} keyboardVerticalOffset={100} behavior="padding" enabled>
{mainContent}
</KeyboardAvoidingView>
);
} else {
return (<SafeAreaView style={{ flex: 1 }}>
{mainContent}
</SafeAreaView>)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreServer.Repositories;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
namespace CoreServer {
public class Startup {
public IConfiguration Configuration { get; }
public Startup (IConfiguration configuration) {
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices (IServiceCollection services) {
services.AddMvc ().SetCompatibilityVersion (CompatibilityVersion.Version_2_1);
var key = Configuration.GetSection ("AppSettings").GetSection ("SecretKey").Value;
var secretKey = new SymmetricSecurityKey (Encoding.UTF8.GetBytes (key));
services.AddTransient<AuthRepo> ();
services.AddTransient<TalkRepo> ();
services.AddSingleton(Configuration);
services.AddSignalR();
services.AddCors (options => {
options.AddPolicy ("EnableCORS", builder => {
builder.AllowAnyOrigin ()
.AllowAnyHeader ()
.AllowAnyMethod ()
.AllowCredentials ()
.Build ();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure (IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment ()) {
app.UseDeveloperExceptionPage ();
} else {
app.UseHsts ();
}
app.UseCors ("EnableCORS");
// app.UseHttpsRedirection();
//app.UseAuthentication ();
app.UseMvc ();
app.UseSignalR (builder => { builder.MapHub<ChartHub> ("/chat"); });
}
}
}
ChatController.cs
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CoreServer.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace CoreServer.Controllers {
[Route ("api/[controller]")]
[ApiController]
public class ChatController : ControllerBase {
private IHubContext<ChartHub> _hub;
public ChatController (IHubContext<ChartHub> hub) {
_hub = hub;
}
public IActionResult Get () {
var timerManager = new TimerManager (() => _hub.Clients.All.SendAsync ("transferchartdata", DataManager.GetData ()));
return Ok (new { Message = "Request Completed" });
}
}
}
Когда я использую почтальон для подключения, он не имеетлюбая проблема.
Когда я использую реагирование с использованием signalR для подключения, он выдает нулевую ошибку, это то, что я получил на реагирующей консоли.
[2019-11-01T14:06:13.729Z] Debug: Starting HubConnection.
[2019-11-01T14:06:13.730Z] Debug: Starting connection with transfer format 'Text'.
Error while starting connection: null
[2019-11-01T14:06:15.743Z] Error: Failed to start the connection: null
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error
- ... 14 more stack frames from framework internals
=====================================================================================
вот что у меня на дотнет ядре
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action CoreServer.Controllers.ChatController.Get (CoreServer) in 268.1478ms
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action CoreServer.Controllers.ChatController.Get (CoreServer) in 268.1478ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 598.9061ms 200 application/json; charset=utf-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 598.9061ms 200 application/json; charset=utf-8
Может кто-нибудьпомогите мне в этом?
======================== Обновлено 11.01 2019
Это ошибкажурнал после обновления сервисов. AddSignalR (o => o.EnableDetailedErrors = true);
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://192.168.111.14:5000/api/chat
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://192.168.111.14:5000/api/chat
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
Policy execution successful.
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution successful.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Route matched with {action = "Get", controller = "Chat"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Get() on controller CoreServer.Controllers.ChatController (CoreServer).
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Get", controller = "Chat"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Get() on controller CoreServer.Controllers.ChatController (CoreServer).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Это журнал ошибок экспо
06
HubConnection {
"cachedPingMessage": "{\"type\":6}",
"callbacks": Object {},
"closedCallbacks": Array [],
"connection": HttpConnection {
"baseUrl": "http://192.168.111.14:5000/api/chat",
"connectionStarted": false,
"connectionState": "Disconnected",
"features": Object {},
"httpClient": DefaultHttpClient {
"httpClient": XhrHttpClient {
"logger": ConsoleLogger {
"minimumLogLevel": 1,
"outputConsole": Object {
"assert": [Function assert],
"debug": [Function __expoConsoleLog],
"error": [Function error],
"group": [Function group],
"groupCollapsed": [Function groupCollapsed],
"groupEnd": [Function groupEnd],
"info": [Function __expoConsoleLog],
"log": [Function __expoConsoleLog],
"warn": [Function warn],
},
},
},
},
"logger": ConsoleLogger {
"minimumLogLevel": 1,
"outputConsole": Object {
"assert": [Function assert],
"debug": [Function __expoConsoleLog],
"error": [Function error],
"group": [Function group],
"groupCollapsed": [Function groupCollapsed],
"groupEnd": [Function groupEnd],
"info": [Function __expoConsoleLog],
"log": [Function __expoConsoleLog],
"warn": [Function warn],
},
},
"onclose": [Function anonymous],
"onreceive": [Function anonymous],
"options": Object {
"WebSocket": [Function WebSocket],
"logMessageContent": false,
"logger": ConsoleLogger {
"minimumLogLevel": 1,
"outputConsole": Object {
"assert": [Function assert],
"debug": [Function __expoConsoleLog],
"error": [Function error],
"group": [Function group],
"groupCollapsed": [Function groupCollapsed],
"groupEnd": [Function groupEnd],
"info": [Function __expoConsoleLog],
"log": [Function __expoConsoleLog],
"warn": [Function warn],
},
},
"skipNegotiation": true,
"transport": 1,
},
},
"connectionStarted": false,
"connectionState": "Disconnected",
"handshakeProtocol": HandshakeProtocol {},
"invocationId": 0,
"keepAliveIntervalInMilliseconds": 15000,
"logger": ConsoleLogger {
"minimumLogLevel": 1,
"outputConsole": Object {
"assert": [Function assert],
"debug": [Function __expoConsoleLog],
"error": [Function error],
"group": [Function group],
"groupCollapsed": [Function groupCollapsed],
"groupEnd": [Function groupEnd],
"info": [Function __expoConsoleLog],
"log": [Function __expoConsoleLog],
"warn": [Function warn],
},
},
"methods": Object {},
"protocol": JsonHubProtocol {
"name": "json",
"transferFormat": 1,
"version": 1,
},
"receivedHandshakeResponse": false,
"reconnectPolicy": undefined,
"reconnectedCallbacks": Array [],
"reconnectingCallbacks": Array [],
"serverTimeoutInMilliseconds": 30000,
}
INFO
10:06
[2019-11-01T15:06:19.386Z] Debug: Starting HubConnection.
INFO
10:06
[2019-11-01T15:06:19.388Z] Debug: Starting connection with transfer format 'Text'.
INFO
10:06
[2019-11-01T15:06:19.515Z] Debug: HubConnection failed to start successfully because of error 'null'.
INFO
10:06
Error while starting connection: null
ERROR
10:06
[2019-11-01T15:06:19.495Z] Error: Failed to start the connection: null
Stack trace:
node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error
node_modules\@aspnet\signalr\dist\cjs\Utils.js:205:45 in log
node_modules\@aspnet\signalr\dist\cjs\HttpConnection.js:306:40 in <unknown>
node_modules\@aspnet\signalr\dist\cjs\HttpConnection.js:34:27 in step
node_modules\@aspnet\signalr\dist\cjs\HttpConnection.js:7:65 in rejected
node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
node_modules\promise\setimmediate\core.js:123:25 in <unknown>
node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152:14 in _callTimer
node_modules\react-native\Libraries\Core\Timers\JSTimers.js:200:17 in _callImmediatesPass
node_modules\react-native\Libraries\Core\Timers\JSTimers.js:473:30 in callImmediates
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:337:6 in __callImmediates
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in <unknown>
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:314:10 in __guard
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:17 in flushedQueue