一个html创建一个websocket,创建一个“ Hello World” WebSocket示例

我在任何地方(截至1月19日)都找不到一个简单的工作示例,所以这里是更新版本。我的Chrome版本为71.0.3578.98。

C#Websocket服务器:

using System;

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.Security.Cryptography;

namespace WebSocketServer

{

class Program

{

static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

static void Main(string[] args)

{

serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));

serverSocket.Listen(1); //just one socket

serverSocket.BeginAccept(null, 0, OnAccept, null);

Console.Read();

}

private static void OnAccept(IAsyncResult result)

{

byte[] buffer = new byte[1024];

try

{

Socket client = null;

string headerResponse = "";

if (serverSocket != null && serverSocket.IsBound)

{

client = serverSocket.EndAccept(result);

var i = client.Receive(buffer);

headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);

// write received data to the console

Console.WriteLine(headerResponse);

Console.WriteLine("=====================");

}

if (client != null)

{

/* Handshaking and managing ClientSocket */

var key = headerResponse.Replace("ey:", "`")

.Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......

.Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==

.Trim();

// key should now equal dGhlIHNhbXBsZSBub25jZQ==

var test1 = AcceptKey(ref key);

var newLine = "\r\n";

var response = "HTTP/1.1 101 Switching Protocols" + newLine

+ "Upgrade: websocket" + newLine

+ "Connection: Upgrade" + newLine

+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine

//+ "Sec-WebSocket-Protocol: chat, superchat" + newLine

//+ "Sec-WebSocket-Version: 13" + newLine

;

client.Send(System.Text.Encoding.UTF8.GetBytes(response));

var i = client.Receive(buffer); // wait for client to send a message

string browserSent = GetDecodedData(buffer, i);

Console.WriteLine("BrowserSent: " + browserSent);

Console.WriteLine("=====================");

//now send message to client

client.Send(GetFrameFromString("This is message from server to client."));

System.Threading.Thread.Sleep(10000);//wait for message to be sent

}

}

catch (SocketException exception)

{

throw exception;

}

finally

{

if (serverSocket != null && serverSocket.IsBound)

{

serverSocket.BeginAccept(null, 0, OnAccept, null);

}

}

}

public static T[] SubArray(T[] data, int index, int length)

{

T[] result = new T[length];

Array.Copy(data, index, result, 0, length);

return result;

}

private static string AcceptKey(ref string key)

{

string longKey = key + guid;

byte[] hashBytes = ComputeHash(longKey);

return Convert.ToBase64String(hashBytes);

}

static SHA1 sha1 = SHA1CryptoServiceProvider.Create();

private static byte[] ComputeHash(string str)

{

return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));

}

//Needed to decode frame

public static string GetDecodedData(byte[] buffer, int length)

{

byte b = buffer[1];

int dataLength = 0;

int totalLength = 0;

int keyIndex = 0;

if (b - 128 <= 125)

{

dataLength = b - 128;

keyIndex = 2;

totalLength = dataLength + 6;

}

if (b - 128 == 126)

{

dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);

keyIndex = 4;

totalLength = dataLength + 8;

}

if (b - 128 == 127)

{

dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);

keyIndex = 10;

totalLength = dataLength + 14;

}

if (totalLength > length)

throw new Exception("The buffer length is small than the data length");

byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };

int dataIndex = keyIndex + 4;

int count = 0;

for (int i = dataIndex; i < totalLength; i++)

{

buffer[i] = (byte)(buffer[i] ^ key[count % 4]);

count++;

}

return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);

}

//function to create  frames to send to client

///

/// Enum for opcode types

///

public enum EOpcodeType

{

/* Denotes a continuation code */

Fragment = 0,

/* Denotes a text code */

Text = 1,

/* Denotes a binary code */

Binary = 2,

/* Denotes a closed connection */

ClosedConnection = 8,

/* Denotes a ping*/

Ping = 9,

/* Denotes a pong */

Pong = 10

}

/// Gets an encoded websocket frame to send to a client from a string

/// The message to encode into the frame

/// The opcode of the frame

/// Byte array in form of a websocket frame

public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)

{

byte[] response;

byte[] bytesRaw = Encoding.Default.GetBytes(Message);

byte[] frame = new byte[10];

int indexStartRawData = -1;

int length = bytesRaw.Length;

frame[0] = (byte)(128 + (int)Opcode);

if (length <= 125)

{

frame[1] = (byte)length;

indexStartRawData = 2;

}

else if (length >= 126 && length <= 65535)

{

frame[1] = (byte)126;

frame[2] = (byte)((length >> 8) & 255);

frame[3] = (byte)(length & 255);

indexStartRawData = 4;

}

else

{

frame[1] = (byte)127;

frame[2] = (byte)((length >> 56) & 255);

frame[3] = (byte)((length >> 48) & 255);

frame[4] = (byte)((length >> 40) & 255);

frame[5] = (byte)((length >> 32) & 255);

frame[6] = (byte)((length >> 24) & 255);

frame[7] = (byte)((length >> 16) & 255);

frame[8] = (byte)((length >> 8) & 255);

frame[9] = (byte)(length & 255);

indexStartRawData = 10;

}

response = new byte[indexStartRawData + length];

int i, reponseIdx = 0;

//Add the frame bytes to the reponse

for (i = 0; i < indexStartRawData; i++)

{

response[reponseIdx] = frame[i];

reponseIdx++;

}

//Add the data bytes to the response

for (i = 0; i < length; i++)

{

response[reponseIdx] = bytesRaw[i];

reponseIdx++;

}

return response;

}

}

}

客户端html和javascript:

/p>

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

var socket = new WebSocket('ws://localhost:8080/websession');

socket.onopen = function() {

// alert('handshake successfully established. May send data now...');

socket.send("Hi there from browser.");

};

socket.onmessage = function (evt) {

//alert("About to receive data");

var received_msg = evt.data;

alert("Message received = "+received_msg);

};

socket.onclose = function() {

alert('connection closed');

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值