Implementation of WebSocket with C # asp.net MVC

Source: Internet
Author: User

With C # asp.net MVC implementation websocket, for WebSocket must have been very understanding, not much to say.

Things do very rough only to achieve basic chat function, but the basic communication is realized, then the expansion of the sequence should not be difficult (personally think so ...)

First look at the effect

Can support both group chat and private chat source download address

http://download.csdn.net/detail/formularz/4668280

First of all, introduce the next ValueWebSocket.cs this file is mainly for communication with the client centralized control

1.valueserver:socket Service Side

2.ValueProtocol: Parsing the data of websocket communication

3.SessionManager: Centrally manage online users ValueWebSocket.cs

  

ValueWebSocket.cs public class Valuewebsocket {//WebSocket service-side private valueserver server;//Resolution Protocol private VALUEPROTOCOL Valueprotocol; Manage online users private SessionManager SessionManager; Public Valuewebsocket (String IPAddress, Int32 port) {valueprotocol = new Valueprotocol (); sessionmanager = new Sessionman Ager (); Server = new Valueserver (ipaddress, Port, Encoding.UTF8); Server. OnReceive + = new ValueHelper.ValueSocket.Infrastructure.ReceiveHandler (server_onreceive); } private void Server_onreceive (ValueHelper.ValueSocket.SocketEvents.ReceiveEventArgs e) {//parse whether the user already exists if ( Sessionmanager.checksessionexist (E.socket)) {Message message = Valueprotocol.decode (E.data); if ( Message.header.Opcode = = opertype.close) {removeuser (e.socket);} if (Message.header.Opcode = = Opertype.text) {String ms g = message. Data.tostring (); Execmsg (E.socket, msg); }} else {//user does not exist add user//and send handshake information connect with client String request = Encoding.UTF8.GetString (E.data); byte[] Response = valueprotocol.getresponse (request);Server. Send (E.socket, response); Sessionmanager.addsession (e.socket, request); Processing of messages private void execmsg (socket socket, String message) {string name = String.Empty; foreach (Valuesession se Ssion in Sessionmanager.sessions} {Socket SK = session. Socket; if (SK. Connected) {if (SK. Remoteendpoint = = socket. Remoteendpoint) {name = session. cookies["Name"]; Break }}//Judge private chat or public string[] Separator = message. Split (new string[] {"<separator>"}, Stringsplitoptions.none); String msg = String.Concat (name, ":", separator[1]); if (separator[0] = = "All") Sendtoall (msg); else {foreach (valuesession session into Sessionmanager.sessions) {if session. cookies["name"] = = Separator[0]) {SendTo (session. Socket, MSG); Break }} private void Removeuser (socket socket) {sessionmanager.removesession (socket);} private void Sendtoall (String msg {foreach (valuesession session in Sessionmanager.sessions) {SendTo. Socket, MSG); } private Boolean SendTo (socket socket, StrinG msg) {byte[] data = Valueprotocol.encode (msg); Send (socket, data); public void Start () {server. Start (); public void Dispose () {sessionmanager.dispose (); server. Dispose (); } }

SessionManager: This class is not much said, centralized management of user classes. See source for details.

Valueprotocol: This class is actually just an interface class,

The real parsing of the data is the ProtocolDraft10 class (the data is parsed according to the rules described in draft 10, note: The agreement indicates that interested students can view this Daniel's article http://blog.csdn.net/fenglibing/article /details/6852497) ProtocolDraft10.cs

  

ProtocolDraft10.cs public class Protocoldraft10:iprotocol {Private Const String Websocketkeypattern = @ "Sec\-websocket\ -key:\s+ (? <key>.*) \ r \ n "; Private Const String Magickey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; Private Const Char Charone = ' 1 '; Private Const Char Charzero = ' 0 '; #region Handshake//Send reply message complete handshake public byte[] Produceresponse (String request) {string Websocketkey = Common.getregexvalue (Request, Websocketkeypattern) [0]. groups["Key"]. Value; String Acceptkey = Produceacceptkey (Websocketkey); StringBuilder StringBuilder = new StringBuilder (); Stringbuilder.append (String.Concat ("http/1.1 Web Socket Protocol handshake", Environment.NewLine)); Stringbuilder.append (String.Concat ("Upgrade:websocket", Environment.NewLine)); Stringbuilder.append (String.Concat ("Connection:upgrade", Environment.NewLine)); Stringbuilder.append (String.Concat ("sec-websocket-accept:", Acceptkey, Environment.NewLine, Environment.NewLine)) ; The String ASD = stringbuilder.tostring (); ReturnEncoding.UTF8.GetBytes (Stringbuilder.tostring ()); Sec-websocket-key and Magickey generated Acceptkey private string Produceacceptkey (String websocketkey) {byte[] Acceptkey = SH A1. Create (). ComputeHash (Encoding.ASCII.GetBytes (Websocketkey + magickey)); Return convert.tobase64string (Acceptkey); #endregion #region Decode//data sent to the client resolves public message Decode (byte[] data) {byte[] buffer = new BYTE[14]; if (data.l Ength >=) buffer.blockcopy (data, 0, Buffer, 0, 14); else buffer.blockcopy (data, 0, Buffer, 0, data.) Length); MessageHeader Header = analysehead (buffer); Message

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.