Asp.net uses SignalR to send pictures
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="/static/imghw/default1.png" data-src="~/Scripts/jquery-2.2.2.min.js" class="lazy" / alt="Asp.net uses SignalR to send pictures" >
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(); } }
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 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; // 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(); } }
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" ></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 = '@Session["username"]'; $('#username').html(userName); // 引用自动生成的集线器代理 var chat = $.connection.chatHub; // 定义服务器端调用的客户端sendMessage来显示新消息 chat.client.sendMessage = function (name, message) { // 向页面添加消息 $('#discussion').append('<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</li>'); }; chat.client.receiveImage = function (name, base64) { // 向页面添加消息 $('#discussion').append('<image class = "file-preview-image" style="width:auto;height:100px;" src=' + base64 + '/>'); }; // 设置焦点到输入框 $('#message').focus(); // 开始连接服务器 $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // 调用服务器端集线器的Send方法 chat.server.send(userName, $('#message').val()); // 清空输入框信息并获取焦点 $('#message').val('').focus(); }); }); $("#fileinput").fileinput({ allowedFileExtensions: ["jpg", "png", "gif", "jpeg"], maxImageWidth: 700, maxImageHeight: 700, resizePreference: 'height', maxFileCount: 1, resizeImage: true }); $("#fileinput").on('fileloaded', function (event, file, previewId, index, reader) { var readers = new FileReader(); readers.onloadend = function () { $(".file-preview-image").attr('src', readers.result); }; readers.readAsDataURL(file); }); $('#sendmessage').click(function() { var imagesJson = $('.file-preview-image').map(function() { var $this = $(this); return { image: $this.attr('src'), filename: $this.attr('data-filename') }; }).toArray(); chat.server.sendImage(userName, imagesJson); }); }); // 为显示的消息进行Html编码 function htmlEncode(value) { var encodedValue = $('<p />').text(value).html(); return encodedValue; } </script> </body> </html>
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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.
