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;} }
SenderID Sender ID
Receiverid Recipient ID
MessageType message type Text Voice and so on
Content Message Contents
3. Add Middleware Chatwebsocketmiddleware
1 public class Chatwebsocketmiddleware 2 {3 private static concurrentdictionary<string, System.Net.Web sockets.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} The public async Task Invoke (HttpContext context) is {!context. Websockets.iswebsocketrequest) {_next await. 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 (); 25 if (!_sockets. ContainsKey (Socketid)) (_sockets). TryAdd (Socketid, Currentsocket); //_sockets. Tryremove (Socketid, out dummy); //_sockets. TryAdd (Socketid, Currentsocket); while (true), (CT). iscancellationrequested) (n.) Ring response = await Receivestringasync (currentsocket, CT); Msgtemplate msg = jsonconvert.deserializeobject<msgtemplate> (response); if (string. IsNullOrEmpty (response)) (Currentsocket.state! = Websocketstate.open) 45 {continue; (var socket in _sockets) 53 {54 if (socket. Value.state! = Websocketstate.open) (+ continue; 57} if (socket). Key = = Msg. Receiverid | | Socket. Key = = Socketid) sendstringasync (socket. Value, Jsonconvert.serializeobject (msg), CT); The//_sockets}. Tryremove (Socketid, out dummy); Currentsocket.closeasync (Websocketclosestatus.normalclosure, "Closing", CT); Currentsocket.dispose (); The System.Net.WebSockets.WebSocket socket, string data, Cance, and the private static Task Sendstringasync Llationtoken ct = default (CancellationToken)). {var buffer = Encoding.UTF8.GetBytes (data); 74 var segment = new arraysegment<byte> (buffer); The return socket. SendAsync (segment, Websocketmessagetype.text, True,CT); The Receivestringasync (System.Net.WebSockets.WebSocket Soc), the private static async task<string> Ket, CancellationToken ct = default (CancellationToken)) (+ var buffer = new arraysegment<byte& gt; (new byte[8192]); Bayi using (var ms = new MemoryStream ()) Websocketreceiveresult result; 84 Do-I-Ct. Throwifcancellationrequested (); The result = await socket. Receiveasync (buffer, CT); Ms. Write (buffer. Array, buffer. Offset, result. Count); (!result. Endofmessage); The MS. Seek (0, Seekorigin.begin); 94 if (result. MessageType! = Websocketmessagetype.text) (97} 98 The using (var reader = new StreamReader (MS, Encoding.UTF8)) 100 {101 return await reader. Readtoendasync (); 102}103}104}105}
Control only the recipient can receive the message if (socket. Key = = Msg. Receiverid | | Socket. Key = = Socketid) { await sendstringasync (socket). Value,jsonconvert.serializeobject (msg), CT);}
4. Using Middleware in Startup.cs
App. Usewebsockets (); app. Usemiddleware<chatwebsocketmiddleware> ();
5. Set up the mobile test example here Ionic3 run on the web side
Create a IONIC3 project skip to Novice can click here to view or have ANGULAR2/4 project experience can be seen directly down
(1) Start Ionic project
There were a lot of problems when I created IONIC3 project.
For example, IONIC-CLI initialization project failed to switch to the default npmorg source.
such as ionic serve failure open proxy allow FQ just fine
The interface is the same after the start-up
(2) Create a Chat window dialog specific layout implementation module loading skip directly into the WebSocket implementation
Don't forget to start the Web project before you do so. The link is not available
(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 the content I want to send such as "Hello World" var msgobj = {SenderID: "222", Receive RID: "111", MessageType: "Text", content:msg}; This.ws.send (Json.stringify (msgobj)); }
ws://localhost:56892?sid=222 This is the Websocke service link address SID represents my Websocke unique identity on this side to find this key can find me this client has 6. A session window is also implemented on the Web side
<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>
<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! =) {return; } e.preventdefault (); var message = $ (' #MessageField '). Val (); var msgobj = {SenderID: "111", Receiverid: "222", MessageType: "Te XT ", content:message}; Socket.send (Json.stringify (msgobj)); $ (' #MessageField '). Val ('); }); }); </script>
Basic development complete next look at the effect
7.web and WebApp End conversations
8.webapp Send web Receive
Netcore WebSocket Instant Messenger Example