用C# ASP.NET MVC 實現WebSocket

來源:互聯網
上載者:User

用C# ASP.NET MVC 實現WebSocket ,對於WebSocket想必都很瞭解了,不多說.

東西做的很粗糙 只能實現基本的聊天功能,不過基本的通訊實現了,那麼後序的擴充應該也不難(個人這麼認為...)

先看下效果

可同時支援群聊和私聊 源碼下載地址

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

首先介紹下ValueWebSocket.cs 這個檔案 主要是對與用戶端的通訊進行集中控制

1.ValueServer: Socket服務端

2.ValueProtocol:對WebSocket通訊的資料加以解析

3.SessionManager: 集中管理線上使用者 ValueWebSocket.cs

  
 

ValueWebSocket.cs public class ValueWebSocket { // WebSocket服務端 private ValueServer server; // 解析協議 private ValueProtocol valueProtocol; // 管理線上使用者 private SessionManager sessionManager; public ValueWebSocket(String ipAddress, Int32 port) { valueProtocol = new ValueProtocol(); sessionManager = new SessionManager(); 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) { // 分析使用者是否已存在 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 msg = message.Data.ToString(); execMsg(e.Socket, msg); } } else { // 使用者不存在則添加使用者 // 並發送握手資訊與用戶端建立串連 String request = Encoding.UTF8.GetString(e.Data); Byte[] response = valueProtocol.GetResponse(request); server.Send(e.Socket, response); sessionManager.AddSession(e.Socket, request); } } // 對訊息進行的處理 private void execMsg(Socket socket, String message) { String name = String.Empty; foreach (ValueSession session in SessionManager.Sessions) { Socket sk = session.Socket; if (sk.Connected) { if (sk.RemoteEndPoint == socket.RemoteEndPoint) { name = session.Cookies["name"]; break; } } } // 判斷私聊還是公用 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 in 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(session.Socket, msg); } } private Boolean sendTo(Socket socket, String msg) { Byte[] data = valueProtocol.Encode(msg); return server.Send(socket, data); } public void Start() { server.Start(); } public void Dispose() { sessionManager.Dispose(); server.Dispose(); } }

SessionManager: 該類就不多說了,集中系統管理使用者類.詳情查看源碼.

ValueProtocol: 這個類其實只是一個介面類,

真正對資料進行解析的是ProtocolDraft10類(按草案10中介紹的規則對資料進行解析,注:對協議說明有興趣的同學可以查看這位大牛的文章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 // 發送回複資訊完成握手 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 101 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)); String asd = stringBuilder.ToString(); return Encoding.UTF8.GetBytes(stringBuilder.ToString()); } // 根據Sec-WebSocket-Key和MagicKey產生AcceptKey private String produceAcceptKey(String webSocketKey) { Byte[] acceptKey = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(webSocketKey + MagicKey)); return Convert.ToBase64String(acceptKey); } #endregion #region Decode // 對用戶端發來的資料進行解析 public Message Decode(Byte[] data) { Byte[] buffer = new Byte[14]; if (data.Length >= 14) Buffer.BlockCopy(data, 0, buffer, 0, 14); else Buffer.BlockCopy(data, 0, buffer, 0, data.Length); MessageHeader header = analyseHead(buffer); Message

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.