Detailed explanation of creating NetCore WebSocket instant messaging instance

巴扎黑
Release: 2017-08-08 11:23:49
Original
4998 people have browsed it

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 _sockets = new ConcurrentDictionary();

 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(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(buffer);
  return socket.SendAsync(segment, WebSocketMessageType.Text, true, ct);
 }

 private static async Task ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken))
 {
  var buffer = new ArraySegment(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();
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;

 constructor(private httpService: HttpService) {

 this.msgArr = [];
 }

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

  this.ws.onopen = () => {
  console.log('open');
  };

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

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

  this.ws.onclose = (event) => {
  console.log('close code=' + 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



Copy after login


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!

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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!