?
快捷搜索:  as  test  1111  test aNd 8=8  test++aNd+8=8  as++aNd+8=8  as aNd 8=8

齊博國際免費注冊:實戰 HTML5 WebSocket 聊天室.net實現

?

WebSocket protocol 是HTML5一種新的協議(protocol)。今朝緊測試了三個瀏覽器支持(Chrome,Firefox4,Safari)

客戶端:

var ws = new WebSocket(con);

//與辦事器握手成功

using System.Collections.Generic;

using System.Text;

using System.Net.Sockets;

using Newtonsoft.Json;

using DotNetWebSocket.Engine.Message;

namespace DotNetWebSocket.Engine

{

public delegate void ClientSocketEvent(object sender,MessageEntity me);

public class ClientSocketInstance

{

private byte[] ServerKey1;

private byte[] ServerKey2;

public string name;

public string Name

{

get { return name; }

set { name = value; }

}

public Socket ClientSocket;

public byte[] receivedDataBuffer;

public event ClientSocketEvent NewUserConnection;

public event ClientSocke齊博國際免費注冊tEvent ReceiveData;

public event ClientSocketEvent DisConnection;

public ClientSocketInstance()

{

receivedDataBuffer = new byte[WebSocketProtocol.GetInstance.MaxBufferSize];

ServerKey1 = new byte[4];

ServerKey2 = new byte[4];

}

///

/// 接管數據

///

///

private void Read(IAsyncResult result)

{

if (!ClientSocket.Connected) return;

try

{

// Web Socket pro齊博國際免費注冊tocol: 0x00開首,0xFF結尾

System.Text.UTF8Encoding decoder = new System.Text.UTF8Encoding();

int startIndex = 0;

int endIndex = 0;

//查找起啟位置

while (receivedDataBuffer[startIndex] == 0x00) startIndex++;

// 查找停止位置

endIndex = startIndex + 1;

while (receivedDataBuffer[endIndex] != 0xff && endIndex != WebSocketProtocol.GetInstance.MaxBufferSize - 1) endIndex++;

if (endIndex == WebSocketProtocol.GetInstance.MaxBufferSize - 1) endIndex = WebSocketProtocol.GetInstance.MaxBufferSize;

string messageReceived = decoder.GetString(receivedDataBuffer, startIndex, endIndex - startIndex);

MessageEntity me = JsonConvert.DeserializeObject(messageReceived, typeof(MessageEntity)) as MessageEntity;

if (!string.IsNullOrEmpty(this.Name))

{

ReceiveData(this, me);

}

else if (me.MessageId.ToLower() == "login")

{

if (NewUserConnection != null)

{

this.Name = (Newtonsoft.Json.JsonConvert.DeserializeObject(me.MessageContent,typeof(ChartMessage)) as ChartMessage).Message;

NewUserConnection(this, me);

}

}

/* MessageEntity me=new MessageEntity();

me.MessageContent = messageReceived;

ReceiveData(this, me);*/

Array.Clear(receivedDataBuffer, 0, receivedDataBuffer.Length);

ClientSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null);

}

catch(Exception ex)

{

DisConnection(this,null);

}

}

///

/// 發送與客戶端握手信息

///

///

public voidStartHandshake(IAsyncResult status)

{

int ClientHandshakeLength = (int) status.AsyncState;

byte[] last8Bytes = new byte[8];

Array.Copy(receivedDataBuffer, ClientHandshakeLength - 8, last8Bytes, 0, 8);

ASCIIEncoding decoder = new System.Text.ASCIIEncoding();

string ClientHandshake = decoder.GetString(receivedDataBuffer, 0, ClientHandshakeLength - 8);

string[] ClientHandshakeLines = ClientHandshake.Split(new string[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries);

/*哀求中的Sec-WebSocket-Key1中所有的數字連在一路

* 然后除以空格的個數,獲得結果1。

* 然后從Key齊博國際免費注冊2同樣的獲得結果2,

* 這兩個結果取整后堵截為32位整數,

* 然后轉成大年夜頭的收集順序(Big-Endian),

* 這兩個結果和哀求中著末的8個字節拼在一路,

* 然后謀略MD5。

這個MD5的16字節結果便是辦事器的反饋key*/

//謀略16位的辦事端Key

foreach (string Line in ClientHandshakeLines)

{

if (Line.Contains("Sec-WebSocket-Key1:"))

BuildServerSecKey(1, Line.Substring(Line.IndexOf(":") + 2));

if (Line.Contains("Sec-WebSocket-Key2:"))

BuildServerSecKey(2, Line.Substring(Line.IndexOf(":") + 2));

}

//握手頭信息

byte[] HandshakeText = Encoding.ASCII.GetBytes(WebSocketProtocol.GetInstance.ServerHandshake);

byte[] serverHandshakeResponse = new byte[HandshakeText.Length + 16];

byte[] serverKey = BuildFullServerSecKey(last8Bytes);

Array.Copy(HandshakeText, serverHandshakeResponse, HandshakeText.Length);

Array.Copy(serverKey, 0, serverHandshakeResponse, HandshakeText.Length, 16);

ClientSocket.BeginSend(serverHandshakeResponse, 0, HandshakeText.Length + 16, 0, HandshakeSuccess, null);

}

///

/// 根據客戶端握手Key天生客戶端相應給客戶真個安然Key

///

///

///

private void BuildServerSecKey(int keyNum, string clientKey)

{

string partialServerKey = "";

byte[] currentKey;

int spacesNum = 0;

char[] keyChars = clientKey.ToCharArray();

//根據客戶端Key獲取得此中的空格數及此中的數字

foreach (char currentChar in keyChars)

{

if (char.IsDigit(currentChar)) partialServerKey += currentChar;

if (char.IsWhiteSpace(currentChar)) spacesNum++;

}

try

{

//用獲取的數字除于空格數,再轉成大年夜頭收集數據

currentKey = BitConverter.GetBytes((int)(Int64.Parse(partialServerKey) / spacesNum));

if (BitConverter齊博國際免費注冊.IsLittleEndian) Array.Reverse(currentKey);

if (keyNum == 1) ServerKey1 = currentKey;

else ServerKey2 = currentKey;

}

catch

{

if (ServerKey1 != null) Array.Clear(ServerKey1, 0, ServerKey1.Length);

if (ServerKey2 != null) Array.Clear(ServerKey2, 0, ServerKey2.Length);

}

}

///

///天生完備的16位安然Key[將Key1和Key2加在一路再加客戶端握手信息的手八位] MD5后返回

///

///

private byte[] BuildFullServerSecKey(byte[] last8Bytes)

{

byte[] concatenatedKeys = new byte[16];

Array.Copy(ServerKey1, 0, concatenatedKeys, 0, 4);

Array.Copy(ServerKey2, 0, concatenatedKeys, 4, 4);

Array.Copy(last8Bytes, 0, concatenatedKeys, 8, 8);

// MD5 Hash

System.Security.Cryptography.MD5 MD5Service = System.Security.Cryptography.MD5.Create();

return MD5Service.ComputeHash(concatenatedKeys);

}

///

/// 握手成功,此時客戶端與辦事端建立接連,可進行通訊

///

///

private void HandshakeSuccess(IAsyncResult result)

{

ClientSocket.EndSend(result);

ClientSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null);

}

///

/// 發送消息

///

///

public void SendMessage(MessageEntity me)

{

ClientSocket.Send(new byte[] {0x00});

ClientSocket.Send(Encoding.UTF8.GetBytes(JsonConvert.Seri齊博國際免費注冊alizeObject(me)));

ClientSocket.Send(new byte[] { 0xff });

}

}

免責聲明:以上內容源自網絡,版權歸原作者所有,如有侵犯您的原創版權請告知,我們將盡快刪除相關內容。

您可能還會對下面的文章感興趣:

浙江体彩20选5开奖号 棋牌游戏交易平台 哈灵麻将下载 pk10 互联网理财平台 3d开机号家彩网 山水云南麻将昆明软烂 湖北快三遗漏数据统计 湖北十一选五遗漏号 羽毛球赛事直播 水力股票推荐 闲来南昌麻将下载 中国女子篮球比赛直 长沙麻将高级技巧 nba各队球员名单 长春科乐2毛麻将群 2019上证指数查询