Home > Backend Development > C#.Net Tutorial > Asp.net uses SignalR to send pictures

Asp.net uses SignalR to send pictures

高洛峰
Release: 2018-05-28 16:22:20
Original
3245 people have browsed it

1. Introduction
In the previous article, we have introduced how to use SignalR to implement the chat room function. In this article, we will implement how to use SignalR to implement the function of sending pictures.

2. The idea of ​​​​implementing the function of sending pictures
I will tell this article in the same way as before. First, let us clarify the idea of ​​​​implementing the function of sending pictures.

  In addition to directly specifying the path of the image (this implementation method is also called: http URI schema), the image can also be displayed through the Data Uri Schema. This method allows images to be embedded directly in web pages in the form of strings. The form is as follows:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA 
7ljmRAAAAGElEQVQIW2P4DwcMDAxAfBvMAhEQMYgcACEHG8ELxtbPAAAAAElFTkSuQmCC" />
Copy after login

 The above code uses Data Url Schema to display images. The advantages and disadvantages of Data Uri Schema are:

Advantages:
It can reduce Http requests, because if you use http Uri Schema to specify the image address, the client needs to issue Http requests for each image, by using Data Uri This method can save bandwidth and HTTP requests

Disadvantages:

 It is only supported by IE8 and above, and the size limit cannot exceed 32KB.
In addition, Base64 content will increase the size of the image by 33%, but GZIP compression can be enabled on the server to reduce the size of the content. Despite this, since sending an Http request will attach a lot of additional information (such as Http Header, etc.), the cumulative content size is still larger than the content added by using Base64 encoding.

Since SignalR is based on text transmission, it is necessary to send pictures.

                 You can only send the Base64-encoded string of the picture to the SignalR server, and then the server will push the Base64 string to the client that needs to receive the picture, and the client will then use the Data Uri method to display the picture on the page, thus Complete the transfer of pictures.
  Of course, you can also upload pictures to Azure Bob Table like Jabbr (an open source project that uses SignalR to implement instant chat), and then return the Uri of the Blob to all clients to display the picture. In fact, this implementation is similar to our implementation here. The client can read the image and display it through the Uri of the blob. In short, the implementation idea is to indirectly convert the content of the image binary file into text for transmission.

3. Implementation code for sending pictures using SignalR
Before the specific implementation, here we need to introduce a file upload plug-in - boostrap-fileinput. This plug-in is used to provide image preview function. For specific usage of the plug-in, please refer to the github site or the implementation code of this article.

1. Implement our hub

public class ChatHub : Hub
  {
    /// <summary>
    /// 供客户端调用的服务器端代码
    /// </summary>
    /// <param name="name"></param>
    /// <param name="message"></param>
    public void Send(string name,string message)
    {
      // 调用所有客户端的sendMessage方法
      Clients.All.sendMessage(name, message);
    }
 
    // 发送图片
    public void SendImage(string name,IEnumerable<ImageData> images)
    {
      foreach (var item in images ?? Enumerable.Empty<ImageData>())
      {
        if(String.IsNullOrEmpty(item.Image)) continue;
        Clients.All.receiveImage(name, item.Image); // 调用客户端receiveImage方法将图片进行显示
      }
    }
 
    /// <summary>
    /// 客户端连接的时候调用
    /// </summary>
    /// <returns></returns>
    public override Task OnConnected()
    {
      Trace.WriteLine("客户端连接成功");
      return base.OnConnected();
    }
  }
Copy after login

2. The implementation code of HomeController mainly generates a random user name for each client, and then stores the user name in the Session.

public class HomeController : Controller
  {
    private static readonly char[] Constant =
    {
      &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;,
      &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;, &#39;m&#39;, &#39;n&#39;, &#39;o&#39;, &#39;p&#39;, &#39;q&#39;, &#39;r&#39;, &#39;s&#39;, &#39;t&#39;, &#39;u&#39;, &#39;v&#39;,
      &#39;w&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;,
      &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39;, &#39;I&#39;, &#39;J&#39;, &#39;K&#39;, &#39;L&#39;, &#39;M&#39;, &#39;N&#39;, &#39;O&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;R&#39;, &#39;S&#39;, &#39;T&#39;, &#39;U&#39;, &#39;V&#39;,
      &#39;W&#39;, &#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;
    };
 
    // GET: Home
    public ActionResult Index()
    {
      Session["username"] = GenerateRandomName(4);
      return View();
    }
 
    /// <summary>
    /// 产生随机用户名函数
    /// </summary>
    /// <param name="length">用户名长度</param>
    /// <returns></returns>
    private static string GenerateRandomName(int length)
    {
      var newRandom = new System.Text.StringBuilder(62);
      var rd = new Random(DateTime.Now.Millisecond);
      for (var i = 0; i < length; i++)
      {
        newRandom.Append(Constant[rd.Next(62)]);
      }
 
      return newRandom.ToString();
    }
}
Copy after login

3. The next step is to implement the front-end page.

<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <title>使用SignalR实现发送图片</title>
  <link href="/Content/bootstrap.min.css" rel="stylesheet">
  <link href="/Content/bootstrap-fileinput/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
  <p class="container">
    <p>用户名:<p id="username"></p></p>
    <input type="text" id="message" />
    <br/>
    <br />
    <input id="fileinput" type="file">
    <br />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion"></ul>
  </p>
  <script type="text/javascript" src="~/Scripts/jquery-2.2.2.min.js"></script>
  <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
  <script src="~/signalr/hubs"></script>
  <script src="/Scripts/fileinput.js" type="text/javascript"></script>
  <script src="/Scripts/bootstrap.min.js" type="text/javascript"></script>
  <script>
    $(function () {
      var userName = &#39;@Session["username"]&#39;;
      $(&#39;#username&#39;).html(userName);
      // 引用自动生成的集线器代理
      var chat = $.connection.chatHub;
      // 定义服务器端调用的客户端sendMessage来显示新消息
 
      chat.client.sendMessage = function (name, message) {
        // 向页面添加消息
        $(&#39;#discussion&#39;).append(&#39;<li><strong>&#39; + htmlEncode(name)
          + &#39;</strong>: &#39; + htmlEncode(message) + &#39;</li>&#39;);
      };
 
      chat.client.receiveImage = function (name, base64) {
        // 向页面添加消息
        $(&#39;#discussion&#39;).append(&#39;<image class = "file-preview-image" style="width:auto;height:100px;" src=&#39; + base64
          + &#39;/>&#39;);
      };
 
      // 设置焦点到输入框
      $(&#39;#message&#39;).focus();
      // 开始连接服务器
      $.connection.hub.start().done(function () {
        $(&#39;#sendmessage&#39;).click(function () {
          // 调用服务器端集线器的Send方法
          chat.server.send(userName, $(&#39;#message&#39;).val());
          // 清空输入框信息并获取焦点
          $(&#39;#message&#39;).val(&#39;&#39;).focus();
        });
      });
 
      $("#fileinput").fileinput({
        allowedFileExtensions: ["jpg", "png", "gif", "jpeg"],
        maxImageWidth: 700,
        maxImageHeight: 700,
        resizePreference: &#39;height&#39;,
        maxFileCount: 1,
        resizeImage: true
      });
 
      $("#fileinput").on(&#39;fileloaded&#39;, function (event, file, previewId, index, reader) {
        var readers = new FileReader();
        readers.onloadend = function () {
          $(".file-preview-image").attr(&#39;src&#39;, readers.result);
        };
        readers.readAsDataURL(file);
      });
 
      $(&#39;#sendmessage&#39;).click(function() {
        var imagesJson = $(&#39;.file-preview-image&#39;).map(function() {
          var $this = $(this);
          return {
            image: $this.attr(&#39;src&#39;),
            filename: $this.attr(&#39;data-filename&#39;)
          };
        }).toArray();
 
        chat.server.sendImage(userName, imagesJson);
      });
    });
 
  // 为显示的消息进行Html编码
  function htmlEncode(value) {
    var encodedValue = $(&#39;<p />&#39;).text(value).html();
    return encodedValue;
  }
  </script>
   
</body>
</html>
Copy after login

4. Operational effect
After the above three steps, the function of sending pictures using SignalR is already operational. Next, let's take a look at the specific operating effect.

Asp.net uses SignalR to send pictures

Here, the introduction of all the contents of this article is over. Next, we will introduce how to use the Html5 Notification API to implement the reminder function of new messages.

For more articles related to Asp.net using SignalR to send pictures, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template