74

Build a real-time chat app from scratch using Vue.js and C# in 5 minutes

 5 years ago
source link: https://www.tuicool.com/articles/hit/vIRFBbQ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
7zINFnz.jpg!web

Build a real-time chat app from scratch using Vue.js and C# in 5 minutes

Butterfly Server .NET is an open source project that makes it incredibly easy to build real-time apps. This article will show you how to get a real-time chat app working in the next 5 minutes using only 37 lines of server code.

This assumes you have Visual Studio.NET Core , and npm already installed and assumes you have familiarity with developing  .NET Core apps and Vue.js clients.

The End Result

Here is the end result running in three different browsers…

nI3Avy3.gif

Notice the messages are automatically synchronized across all the browsers by Butterfly Server .NET .

Creating the Server

First, create a new .NET Core Console App in Visual Studio called MyChatApp .

Next, install Butterfly.Core and Butterfly.EmbedIO using the Package Manager Console

Install-Package Butterfly.Core
Install-Package Butterfly.EmbedIO

Next, replace Program.cs with this server code…

using System;
using Butterfly.Core.Util;
using Butterfly.EmbedIO;
using Dict = System.Collections.Generic.Dictionary<string, object>;
namespace MyChatApp {
class Program {
static void Main(string[] args) {
using (EmbedIOContext ctx =
new EmbedIOContext("http://+:8000/", "../../../www")) {
// Create a database
        var db = 
          new Butterfly.Core.Database.Memory.MemoryDatabase();
        db.CreateFromTextAsync(@"CREATE TABLE message (
          id VARCHAR(50) NOT NULL,
          text VARCHAR(40) NOT NULL,
          PRIMARY KEY (id)
        );").Wait();
        db.SetDefaultValue("id", _ => Guid.NewGuid().ToString());
// Define the Web API
        ctx.WebApi.OnPost("/api/message/insert", async(req,res) => {
          var message = await req.ParseAsJsonAsync<Dict>();
          await db.InsertAndCommitAsync<string>("message", message);
        });
// Define the Subscription API
        ctx.SubscriptionApi.OnSubscribe("messages",(vars,channel)=>{
          return db.CreateAndStartDynamicViewAsync(
            "SELECT * FROM message",
            dataEvents => channel.Queue(dataEvents)
          );
        });
ctx.Start();
ProcessX.OpenBrowser($"http://localhost:8000/");
Console.ReadLine();
}
}
}
}

The code above…

  • Initializes an EmbedIO webserver to receive HTTP and WebSocket requests on port 8000
  • Creates a Memory Database with a single message table
  • Defines a Web API to handle calls to /api/message/insert to add new messages to the chat
  • Defines a Subscription API to synchronize all records in the message table to connected clients

Creating the Client

First, create a www folder in Visual Studio under your project.

2uu6V3V.png!web

Next, open a command prompt or terminal in the MyChatApp/MyChatApp/www directory and run…

# just accept the defaults
npm init
npm install vue reqwest butterfly-client

Next, create an index.html under the www folder with this content…

<!DOCTYPE html>
<html lang="en">
<body>
<div id="app">
<div style="width: 15rem; margin: 1rem auto;">
<div style="height: 15rem; overflow-y: auto;
background-color: #fafafa; padding: 0.5rem">
<p v-for="message in reverseMessages" :key="message.id">
{{ message.text }}
</p>
</div>
<form style="padding: 0.5rem 0">
<input v-model="text" />
<button @click.prevent="postMessage">Send</button>
</form>
</div>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/reqwest/reqwest.js"></script>
<script src="node_modules/butterfly-client/lib/butterfly-client.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data() {
      return {
        client: null,
        text: null,
        messages: [],
      }
    },
    methods: {
      postMessage() {
        reqwest({
          url: '/api/message/insert',
          method: 'POST',
          data: JSON.stringify({
            text: this.text
          }),
        });
        this.text = '';
      },
    },
    computed: {
      reverseMessages() {
        return this.messages.reverse();
      }
    },
    beforeMount() {
      let butterflyClient = window['butterfly-client'];
      this.client = new butterflyClient.WebSocketChannelClient({
        url: '/ws'
      });
      this.client.connect();
      this.client.subscribe({
        channel: 'messages',
        handler: new butterflyClient.ArrayDataEventHandler({
          arrayMapping: {
            message: this.messages
          }
        })
      });
    }
  })
</script>
</body>
</html>

The code above…

  • Uses Vue.js to render the messages array as paragraph tags
  • Uses reqwest to call /api/message/insert on our server when the Send button is pressed
  • Uses Butterfly Client to create a WebSocketChannelClient instance that connects to the server and subscribes to the messages channel mapping the results to a local messages array

Trying It

In Visual Studio , run MyChatApp . This will start the server and open a browser instance to http://localhost:8000/ .

Try sending a few chat messages.

Next, open more browser instances to http://localhost:8000/ and confirm all the browser instances stay synchronized properly.

Next Steps

Butterfly Server .NET allows you to build much more sophisticated real-time apps with minimal effort. See https://butterflyserver.io for more information.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK