Home Backend Development C#.Net Tutorial Detailed explanation of creating NetCore WebSocket instant messaging instance

Detailed explanation of creating NetCore WebSocket instant messaging instance

Aug 08, 2017 am 11:23 AM
web websocket

This article mainly introduces the NetCore WebSocket instant messaging example in detail, which has certain reference value. Interested friends can refer to

NetCore WebSocket instant messaging example for your reference. The content is as follows

1. Create a new Netcore Web project

2. Create a simple communication protocol


public class MsgTemplate
 {
 public string SenderID { get; set; }
 public string ReceiverID { get; set; }
 public string MessageType { get; set; }
 public string Content { get; set; }
 }
Copy after login

SenderID Sender ID

ReceiverID Receiver ID

MessageType Message Type Text Voice etc.

Content Message content

3. Add middleware ChatWebSocketMiddleware


public class ChatWebSocketMiddleware
 {
 private static ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> _sockets = new ConcurrentDictionary<string, System.Net.WebSockets.WebSocket>();

 private readonly RequestDelegate _next;

 public ChatWebSocketMiddleware(RequestDelegate next)
 {
  _next = next;
 }

 public async Task Invoke(HttpContext context)
 {
  if (!context.WebSockets.IsWebSocketRequest)
  {
  await _next.Invoke(context);
  return;
  }
  System.Net.WebSockets.WebSocket dummy;

  CancellationToken ct = context.RequestAborted;
  var currentSocket = await context.WebSockets.AcceptWebSocketAsync();
  //string socketId = Guid.NewGuid().ToString();
  string socketId = context.Request.Query["sid"].ToString();
  if (!_sockets.ContainsKey(socketId))
  {
  _sockets.TryAdd(socketId, currentSocket);
  }
  //_sockets.TryRemove(socketId, out dummy);
  //_sockets.TryAdd(socketId, currentSocket);

  while (true)
  {
  if (ct.IsCancellationRequested)
  {
   break;
  }

  string response = await ReceiveStringAsync(currentSocket, ct);
  MsgTemplate msg = JsonConvert.DeserializeObject<MsgTemplate>(response);

  if (string.IsNullOrEmpty(response))
  {
   if (currentSocket.State != WebSocketState.Open)
   {
   break;
   }

   continue;
  }

  foreach (var socket in _sockets)
  {
   if (socket.Value.State != WebSocketState.Open)
   {
   continue;
   }
   if (socket.Key == msg.ReceiverID || socket.Key == socketId)
   {
   await SendStringAsync(socket.Value, JsonConvert.SerializeObject(msg), ct);
   }
  }
  }

  //_sockets.TryRemove(socketId, out dummy);

  await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
  currentSocket.Dispose();
 }

 private static Task SendStringAsync(System.Net.WebSockets.WebSocket socket, string data, CancellationToken ct = default(CancellationToken))
 {
  var buffer = Encoding.UTF8.GetBytes(data);
  var segment = new ArraySegment<byte>(buffer);
  return socket.SendAsync(segment, WebSocketMessageType.Text, true, ct);
 }

 private static async Task<string> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken))
 {
  var buffer = new ArraySegment<byte>(new byte[8192]);
  using (var ms = new MemoryStream())
  {
  WebSocketReceiveResult result;
  do
  {
   ct.ThrowIfCancellationRequested();

   result = await socket.ReceiveAsync(buffer, ct);
   ms.Write(buffer.Array, buffer.Offset, result.Count);
  }
  while (!result.EndOfMessage);

  ms.Seek(0, SeekOrigin.Begin);
  if (result.MessageType != WebSocketMessageType.Text)
  {
   return null;
  }

  using (var reader = new StreamReader(ms, Encoding.UTF8))
  {
   return await reader.ReadToEndAsync();
  }
  }
 }
 }
Copy after login

Control that only the recipient can receive the message


##

if (socket.Key == msg.ReceiverID || socket.Key == socketId)
{
 await SendStringAsync(socket.Value,JsonConvert.SerializeObject(msg), ct);
}
Copy after login

4. Use in Startup.cs Middleware


app.UseWebSockets();
app.UseMiddleware<ChatWebSocketMiddleware>();
Copy after login

5. Establish a mobile terminal test example. Here Ionic3 is used to run on the web terminal

Create an ionic3 project. Novices can click here to view it. Or if you have The Angular2/4 project can be viewed directly

(1) Start the Ionic project

I encountered many problems when I created the ionic3 project

For example, if the ionic-cli initialization project fails, just switch to the default npmorg source.

For example, if ionic serve fails, just open the proxy and allow FQ.

The interface after startup is like this

(2) Create a chat window dialog. Skip the loading of the specific layout implementation module and go directly to the websocket implementation.

Don’t forget to start the web project before this, otherwise this will happen. The situation cannot be linked to the service

(3)dialog.ts specific implementation


export class Dialog {

 private ws: any;
 private msgArr: Array<any>;

 constructor(private httpService: HttpService) {

 this.msgArr = [];
 }

 ionViewDidEnter() {
 if (!this.ws) {
  this.ws = new WebSocket("ws://localhost:56892?sid=222");

  this.ws.onopen = () => {
  console.log(&#39;open&#39;);
  };

  this.ws.onmessage = (event) => {
  console.log(&#39;new message: &#39; + event.data);
  var msgObj = JSON.parse(event.data);
  this.msgArr.push(msgObj);;
  };

  this.ws.onerror = () => {
  console.log(&#39;error occurred!&#39;);
  };

  this.ws.onclose = (event) => {
  console.log(&#39;close code=&#39; + event.code);
  };
 }
 }

 sendMsg(msg) {//msg为我要发送的内容 比如"hello world"
 var msgObj = {
  SenderID: "222",
  ReceiverID: "111",
  MessageType: "text",
  Content: msg
 };
 this.ws.send(JSON.stringify(msgObj));
 }
Copy after login

ws://localhost: 56892?sid=222 This is the websocke service link address

sid represents the unique identification of WebSocke on my end. If you find this key, you can find my client.

6. Also implemented on the web side A session window



<p class="container" style="width:90%;margin:0px auto;border:1px solid steelblue;">
 <p class="msg">
 <p id="msgs" style="height:200px;"></p>
 </p>

 <p style="display:block;width:100%">
 <input type="text" style="max-width:unset;width:100%;max-width:100%" id="MessageField" placeholder="type message and press enter" />
 </p>
</p>
Copy after login


<script>
 $(function () {
  $(&#39;.navbar-default&#39;).addClass(&#39;on&#39;);

  var userName = &#39;@Model&#39;;

  var protocol = location.protocol === "https:" ? "wss:" : "ws:";
  var wsUri = protocol + "//" + window.location.host + "?sid=111";
  var socket = new WebSocket(wsUri);
  socket.onopen = e => {
  console.log("socket opened", e);
  };

  socket.onclose = function (e) {
  console.log("socket closed", e);
  };

  socket.onmessage = function (e) {
  console.log(e);
  var msgObj = JSON.parse(e.data);
  $(&#39;#msgs&#39;).append(msgObj.Content + &#39;<br />&#39;);
  };

  socket.onerror = function (e) {
  console.error(e.data);
  };

  $(&#39;#MessageField&#39;).keypress(function (e) {
  if (e.which != 13) {
   return;
  }

  e.preventDefault();

  var message = $(&#39;#MessageField&#39;).val();

  var msgObj = {
   SenderID:"111",
   ReceiverID:"222",
   MessageType: "text",
   Content: message
  };
  socket.send(JSON.stringify(msgObj));
  $(&#39;#MessageField&#39;).val(&#39;&#39;);
  });
 });
 </script>
Copy after login
Basically developed, let’s see the effect

7.web and webapp side dialogue

8.webapp sends web receives

9. So much has been achieved so far because the project also involves other technologies and is not open source for the time being

The above is the detailed content of Detailed explanation of creating NetCore WebSocket instant messaging instance. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

How to use Java and WebSocket to implement real-time stock quotation push How to use Java and WebSocket to implement real-time stock quotation push Dec 17, 2023 pm 09:15 PM

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

golang WebSocket programming tips: handling concurrent connections golang WebSocket programming tips: handling concurrent connections Dec 18, 2023 am 10:54 AM

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb

How to use WebSocket for file transfer in golang How to use WebSocket for file transfer in golang Dec 18, 2023 am 09:06 AM

How to use WebSocket for file transfer in golang WebSocket is a network protocol that supports two-way communication and can establish a persistent connection between the browser and the server. In golang, we can use the third-party library gorilla/websocket to implement WebSocket functionality. This article will introduce how to use golang and gorilla/websocket libraries for file transfer. First, we need to install gorilla

See all articles