使用ASP.NET Core SignalR和React做1个简单聊天应用程序

本文将使用ASP.NET Core SignalR和React.js做一个简单聊天应用程序,服务器端使用ASP.NET Core SignalR来实现,客户端使用React.js来实现。

本文将使用ASP.NET Core SignalR和React.js做一个简单聊天应用程序,服务器端使用ASP.NET Core SignalR来实现,客户端使用React.js来实现。

ASP.NET Core SignalR和React做一个简单聊天应用程序

In one of the last posts, we saw how we can make a simple chat with ASP.NET Core SignalR and Angular 5. This time, we will use the same code from the backend and swap Angular with React on the frontend.

使用ASP.NET Core SignalR和React做一个简单聊天应用程序
ASP.NET Core SignalR和React

There is also a post about making a simple SignalR app with pure ASP.NET Core stack, using Razor Pages with vanilla JavaScript on the client – ASP.NET Core SignalR simple chat.

Most of the code should be the same, and because of that, we will focus mostly on the client side.

在最后一个帖子中,我们看到了如何与ASP.NET Core SignalR和角5进行简单的聊天。这一次,我们将使用来自后端的相同代码,并在前端与 React 交换Angular。

还有一篇关于使用纯ASP.NET核心堆栈制作简单的SignalR应用程序的帖子,在客户端上使用带有香草JavaScript的Razor Pages——ASP.NET核心信号R的简单聊天。

大多数代码应该相同,因此,我们将主要关注客户端。

创建react app

我们将使用创建-反应应用程序,这是一种官方支持的方式,使用 React 创建 SPA 应用程序。它没有配置,但它确实使用网包和巴贝尔引擎盖下。

它易于使用,不需要任何配置,确切地说,您无法配置它。它附带 4 个预定义的脚本:

  • 启动 = 在开发模式下启动应用
  • 测试 = 在交互式监视模式下启动测试流道
  • 生成 = 构建用于生产的应用程序,生成文件夹的输出
  • 弹出 – 作为输出,你会得到你的应用程序文件和配置文件(巴贝尔,网页包,环境,路径等)。弹出应用后,您无法返回,因此无法访问使用无配置创建-反应应用工具的能力。但是,您可以根据需要自定义和配置所有内容。

我们将只使用第一个在这篇文章。

We will use create-react-app, which is an officially supported way to create SPA applications with React. It has no configuration, but it does use Webpack and Babel under the hood.

It is easy to use and requires no configuration, to be precise, you can’t configure it. It comes with 4 predefined scripts:

  • start – starts the app in development mode
  • test – starts test runner in interactive watch mode
  • build – builds the app for production, outputs to build folder
  • eject – as an output, you get your app files + configuration files (babel, webpack, environment, paths etc.). You can’t go back once you eject an app, you lose the ability to use the no-configuration create-react-app tool. However, you can customise and configure everything as you prefer.

We will use only the first one during this post.

React 聊天程序代码

ASP.NET Core SignalR和React我们将使用相同的服务器端代码,因为我们用Angular简单聊天应用

让我们首先创建一个新的空 React 应用程序:

We will use the same server-side code as we did with our simple chat with Angular 5.

Let’s first create a new empty React application:

create-react-app codingblast

现在我们可以立即添加 SignalR npm 包:
Now we can immediately add SignalR npm package:
npm install @aspnet/signalr-client
接下来添加聊天代码:
import React, { Component } from 'react';

class Chat extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      nick: '',
      message: '',
      messages: [],
      hubConnection: null,
    };
  }

  render() {
    return <div>Here goes chat</div>;
  }
}

export default Chat;

我们使用的属性与使用 Angular 聊天时相同。我们只需要 nick、消息、消息和 HubConnect。

第一个是用户的昵称,第二个是当前消息被键入到输入,消息是用于我们从服务器接收的所有消息。

用户的昵称和与服务器的连接,我们只需要设置一次,在开始。因此,我们将添加组件 DidMount 生命周期方法:

We are using the same properties as we did with Angular chat. We only need nick, message, messages and HubConnection.

First is the user’s nickname, second is the current message being typed to the input, messages are for all the messages that we receive from the server.

The user’s nickname and the connection to the server we only need to set up once, at the start. Hence, we will add the componentDidMount lifecycle method:

componentDidMount = () => {
    const nick = window.prompt('Your name:', 'John');

    const hubConnection = new HubConnection('http://localhost:5000/chat');

    this.setState({ hubConnection, nick });
}

设置 nick 和 HubConnect 对象后,应尝试与服务器建立连接:

After we set up the nick and the HubConnection object, we should try to establish the connection with the Server:

componentDidMount = () => {
  const nick = window.prompt('Your name:', 'John');

  const hubConnection = new HubConnection('https://jhrs.com');

  this.setState({ hubConnection, nick }, () => {
    this.state.hubConnection
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));
  });
}

ASP.NET Core SignalR和React实现此目标后,我们现在可以从服务器开始侦听事件。我们将只是在 setState 的回调中扩展我们的代码。我们将添加此代码段:

After that is achieved, we can now start listening for the events from the server. We will just extend our code inside of setState’s callback. We will add this code snippet:

this.state.hubConnection.on('sendToAll', (nick, receivedMessage) => {
  const text = `${nick}: ${receivedMessage}`;
  const messages = this.state.messages.concat([text]);
  this.setState({ messages });
});

让我们来看看我们的聊天组件,它目前的样子:

Let’s take a look at our Chat component, how it looks at the moment:

import React, { Component } from 'react';
import { HubConnection } from '@aspnet/signalr-client';

class Chat extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      nick: '',
      message: '',
      messages: [],
      hubConnection: null,
    };
  }

  componentDidMount = () => {
    const nick = window.prompt('Your name:', 'John');

    const hubConnection = new HubConnection('http://localhost:5000/chat');

    this.setState({ hubConnection, nick }, () => {
      this.state.hubConnection
        .start()
        .then(() => console.log('Connection started!'))
        .catch(err => console.log('Error while establishing connection :('));

      this.state.hubConnection.on('sendToAll', (nick, receivedMessage) => {
        const text = `${nick}: ${receivedMessage}`;
        const messages = this.state.messages.concat([text]);
        this.setState({ messages });
      });
    });
  }
  
  render() {
    return <div>Here goes chat</div>;
  }
}

export default Chat;

ASP.NET Core SignalR和React看起来不错现在,我们需要添加向服务器发送消息的逻辑。此外,我们需要在视图中显示实际消息和用于发送消息的按钮。

我们将保持发送消息的方法简单:

That seems fine. Now, we need to add the logic for sending messages to the server. Also, we need to show the actual messages in the view and the button for sending messages.

We will keep the method for sending messages simple:

sendMessage = () => {
  this.state.hubConnection
    .invoke('sendToAll', this.state.nick, this.state.message)
    .catch(err => console.error(err));

    this.setState({message: ''});      
};

发送消息后,我们可以清除输入和消息属性。

下面是完成聊天组件的视图:

After we sent the message, we can clear out the input – message property.

Here is the view to finish our Chat component:

render() {
  return (
    <div>
      <br />
      <input
        type="text"
        value={this.state.message}
        onChange={e => this.setState({ message: e.target.value })}
      />

      <button onClick={this.sendMessage}>Send</button>

      <div>
        {this.state.messages.map((message, index) => (
          <span style={{display: 'block'}} key={index}> {message} </span>
        ))}
      </div>
    </div>
  );
}

代码示例

您可以在 GitHub 上找到ASP.NET Core SignalR和React代码示例:ASP.NET Core SignalR Chat

您可以在此存储库上逐步找到 (提交): AspNetCoreSignalR_React

本文翻译自:https://codingblast.com/asp-net-core-signalr-chat-react/

本文关键字:React 聊天程序,ASP.NET Core SignalR和React

猜你喜欢

本站最新优惠

Namesilo优惠:新用户省 $1 域名注册-优惠码:45D%UYTcxYuCloZ 国外最便宜域名!点击了解更多

特别优惠:免费赠送 $100 Vultr主机-限时优惠!英文站必备海外服务器!点击了解更多

VPS优惠:搬瓦工优惠码:BWH3OGRI2BMW 最高省5.83%打开外面世界的一款主机点击了解更多

加入电报群

【江湖人士】(jhrs.com) 投稿作者:IT菜鸟,不代表江湖人士立场,如若转载,请注明出处:https://jhrs.com/2020/36703.html

扫码加入电报群,让你获得国外网赚一手信息。

文章标题:使用ASP.NET Core SignalR和React做1个简单聊天应用程序

(0)
IT菜鸟的头像IT菜鸟普通会员
上一篇 2020-06-02 17:39
下一篇 2020-06-02 21:28

热门推荐

发表回复

登录后才能评论
畅访海外网站,外贸/外企/科技工作者专用工具,无缝体验真实的互联网,解锁LinkedIn访问
$19.95 /年
直达官网