1. Create a Netcore Web project

2. Create simple communication protocols

public class MsgTemplate
    {
        public string SenderID { get; set; }
        public string ReceiverID { get; set; }
        public string MessageType { get; set; }
        public string Content { get; set; }}Copy the code

SenderID Indicates the ID of the sender

ReceiverID ID of the recipient

MessageType MessageType Text Voice, etc

Content Message Content

3.添加中间件ChatWebSocketMiddleware

  1 public class ChatWebSocketMiddleware
  2     {
  3         private static ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> _sockets = new ConcurrentDictionary<string, System.Net.WebSockets.WebSocket>();
  4 
  5         private readonly RequestDelegate _next;
  6 
  7         public ChatWebSocketMiddleware(RequestDelegate next)
  8         {
  9             _next = next;
 10         }
 11 
 12         public async Task Invoke(HttpContext context)
 13         {
 14             if(! context.WebSockets.IsWebSocketRequest) 15 { 16 await _next.Invoke(context); 17return;
 18             }
 19             System.Net.WebSockets.WebSocket dummy;
 20 
 21             CancellationToken ct = context.RequestAborted;
 22             var currentSocket = await context.WebSockets.AcceptWebSocketAsync();
 23             //string socketId = Guid.NewGuid().ToString();
 24             string socketId = context.Request.Query["sid"].ToString();
 25             if(! _sockets.ContainsKey(socketId)) 26 { 27 _sockets.TryAdd(socketId, currentSocket); 28 } 29 //_sockets.TryRemove(socketId, out dummy); 30 //_sockets.TryAdd(socketId, currentSocket); 31 and 32while (true{33) 34if (ct.IsCancellationRequested)
 35                 {
 36                     break; 37 } 38 39 string response = await ReceiveStringAsync(currentSocket, ct); 40 MsgTemplate msg = JsonConvert.DeserializeObject<MsgTemplate>(response); 41 and 42if (string.IsNullOrEmpty(response))
 43                 {
 44                     if(currentSocket.State ! = WebSocketState.Open) 45 { 46break; 47} 48 and 49continue;
 50                 }
 51 
 52                 foreach (var socket in _sockets)
 53                 {
 54                     if(socket.Value.State ! = WebSocketState.Open) 55 { 56continue; 57} 58if (socket.Key == msg.ReceiverID || socket.Key == socketId)
 59                     {
 60                         await SendStringAsync(socket.Value, JsonConvert.SerializeObject(msg), ct);
 61                     }
 62                 }
 63             }
 64 
 65             //_sockets.TryRemove(socketId, out dummy);
 66 
 67             await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
 68             currentSocket.Dispose();
 69         }
 70 
 71         private static Task SendStringAsync(System.Net.WebSockets.WebSocket socket, string data, CancellationToken ct = default(CancellationToken))
 72         {
 73             var buffer = Encoding.UTF8.GetBytes(data);
 74             var segment = new ArraySegment<byte>(buffer);
 75             return socket.SendAsync(segment, WebSocketMessageType.Text, true, ct);
 76         }
 77 
 78         private static async Task<string> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken))
 79         {
 80             var buffer = new ArraySegment<byte>(new byte[8192]);
 81             using (var ms = new MemoryStream())
 82             {
 83                 WebSocketReceiveResult result;
 84                 do85 { 86 ct.ThrowIfCancellationRequested(); 87 88 result = await socket.ReceiveAsync(buffer, ct); 89 ms.Write(buffer.Array, buffer.Offset, result.Count); 90} 91while(! result.EndOfMessage); 92 93 ms.Seek(0, SeekOrigin.Begin); 94if(result.MessageType ! = WebSocketMessageType.Text) 95 { 96return null;
 97                 }
 98 
 99                 using (var reader = new StreamReader(ms, Encoding.UTF8))
100                 {
101                     returnawait reader.ReadToEndAsync(); 102} 103} 104} 105}Copy the code

Controls that only the receiver can receive the messageif (socket.Key == msg.ReceiverID || socket.Key == socketId)
{
     await SendStringAsync(socket.Value,JsonConvert.SerializeObject(msg), ct);
}Copy the code

4. Use middleware in startup. cs

app.UseWebSockets();
app.UseMiddleware<ChatWebSocketMiddleware>();Copy the code

5. Set up a mobile terminal test example Ionic3 is used to run on the web terminal

Creating an ionic3 project can be viewed here for beginners who skipped it, or directly below for those with experience in angular2/4 projects

(1) Start the Ionic project

We had a lot of problems when we started ionic3

For example ionic- CLI initialization project fails switch to default NPMORG source

Ionic serve, for example, fails to open the proxy to allow scaling over the wall

This is what the interface looks like when it starts up

(2) Create chat window dialog specific layout implementation module load skipped directly into the Websocket implementation

Don’t forget to start your Web project before you do that or you’ll have a situation where you can’t connect to the service

(3) Dialog.ts concrete 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('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 is what I want to send for example"hello world"
        var msgObj = {
            SenderID: "222",
            ReceiverID: "111",
            MessageType: "text",
            Content: msg
        };
        this.ws.send(JSON.stringify(msgObj));
    }Copy the code

ws://localhost:56892? Sid =222 This is the webSocke service link address
Sid represents the unique identifier of my WebSocke and finding this key will lead you to my client
6. Implement a session window on the Web
<div class="container" style="width:90%; margin:0px auto; border:1px solid steelblue;">
    <div class="msg">
        <div id="msgs" style="height:200px;"></div>
    </div>

    <div 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" />
    </div>
</div>Copy the code

<script>
        $(function() {$('.navbar-default').addClass('on');

            var userName = '@Model';

            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);
                $('#msgs').append(msgObj.Content + '<br />');
            };

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

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

                e.preventDefault();

                var message = $('#MessageField').val();

                var msgObj = {
                    SenderID:"111",
                    ReceiverID:"222",
                    MessageType: "text",
                    Content: message
                };
                socket.send(JSON.stringify(msgObj));
                $('#MessageField').val(' ');
            });
        });
    </script>Copy the code

Basic development is done and then let’s see what happens

7. The Web communicates with the WebApp

8. Webapp sends and Receives web messages

9. That’s all we’ve achieved so far because the project involves other technologies and is closed to open source for now