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/imghwm/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!

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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