This article is mainly for you to introduce the Netcore WebSocket real-time communication example, with a certain reference value, interested in small partners can refer to
Netcore WebSocket Instant Messenger sample, for your reference, the specific 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 Messa Getype {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
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) {I F (!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 (); } } } }
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 can look straight 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) {T His.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, such as "Hello World" var msgobj = { SenderID: "222", Receiverid: "111", MessageType: "Text", content:msg} ; This.ws.send (Json.stringify (msgobj)); }
ws://localhost:56892?sid=222 This is the Websocke service link address
Sid means my end of the Websocke unique identity find this key can find me this user-side
6. A session window is also implemented on the Web side
<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>
<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: "Text", 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
9. So much has been achieved so far because the project also involves other technologies that are temporarily not open source.