iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 16
0
自我挑戰組

What a good thing we lose? What a bad thing we knew?系列 第 16

【Day 16】在Visual Studio 2017 寫一個聊天室

  • 分享至 

  • xImage
  •  

大家好,今天跟大家一起學習 如何寫一個聊天室。

Step 1. 先下載 Microsoft.AspNet.SignalR 套件

https://ithelp.ithome.com.tw/upload/images/20181030/20112000vfPfTOotHZ.png

PM> install-package  Microsoft.AspNet.SignalR

Step 2. 新增 chatHub.cs
https://ithelp.ithome.com.tw/upload/images/20181030/20112000o0mQcjtC8B.png

https://ithelp.ithome.com.tw/upload/images/20181030/20112000Skcazuv2RZ.png

使用以下代碼替換ChatHub類中的代碼。

C#

   using System;
    using System.Web;
    using Microsoft.AspNet.SignalR;
    namespace SignalRChat
    {
        public class ChatHub : Hub
        {
            public void Send(string name, string message)
            {
                // Call the addNewMessageToPage method to update clients.
                Clients.All.addNewMessageToPage(name, message);
            }
        }
    }

Step 3. 新增 startup.cs
https://ithelp.ithome.com.tw/upload/images/20181030/20112000S6dzv3TY19.png

取代 startup.cs 原本內容

 using Owin;
    using Microsoft.Owin;
    [assembly: OwinStartup(typeof(SignalRChat.Startup))]
    namespace SignalRChat
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // Any connection or hub wire up and configuration should go here
                app.MapSignalR();
            }
        }
    }

Step 4. 在HomeController建立chat

    public ActionResult Chat()
    {
        return View();
    }

https://ithelp.ithome.com.tw/upload/images/20181030/20112000SLNoEXuEzY.png

View

@{
    ViewBag.Title = "Chat";
}
<h2>聊天室</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="送出" />
    <input type="hidden" id="displayname" />
    <ul id="discussion"></ul>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.3.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('輸入您的暱稱:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

https://ithelp.ithome.com.tw/upload/images/20181030/20112000RA5clfYfpc.png

Step 5. 成功畫面
https://ithelp.ithome.com.tw/upload/images/20181030/20112000ziYboDjsL0.png

https://ithelp.ithome.com.tw/upload/images/20181030/20112000NUSSRqKI6B.png

https://ithelp.ithome.com.tw/upload/images/20181030/20112000p3gcBcuny0.png

https://ithelp.ithome.com.tw/upload/images/20181030/20112000gckOXKgbSw.png

參考網址:
https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc
https://dotblogs.com.tw/jakeuj/2016/02/15/signalr


上一篇
【Day 15】在Visual Studio 2017 寫一個亂數密碼產生器
下一篇
【Day 17】在Visual Studio 2017 寫一個網址解析器
系列文
What a good thing we lose? What a bad thing we knew?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言