html5 websocket .net,有没有为.NET实现的WebSocket客户端?

这篇博客介绍了一个简单的从Java移植到C#的WebSocket实现。代码仅支持非SSL模式的“ws”协议,尚未进行全面测试。连接建立过程中涉及HTTP握手,包括发送请求头和验证响应头。发送和接收数据的方法也已实现,但注意在进行这些操作前需完成握手。此代码可供学习和参考,但不适用于SSL/TLS加密的WebSocket连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一个快速的第一次传递Java代码到C#。不支持SSL模式,只是经过了很少的测试,但它是一个开始。

using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Text;

public class WebSocket

{

private Uri mUrl;

private TcpClient mClient;

private NetworkStream mStream;

private bool mHandshakeComplete;

private Dictionary mHeaders;

public WebSocket(Uri url)

{

mUrl = url;

string protocol = mUrl.Scheme;

if (!protocol.Equals("ws") && !protocol.Equals("wss"))

throw new ArgumentException("Unsupported protocol: " + protocol);

}

public void SetHeaders(Dictionary headers)

{

mHeaders = headers;

}

public void Connect()

{

string host = mUrl.DnsSafeHost;

string path = mUrl.PathAndQuery;

string origin = "http://" + host;

mClient = CreateSocket(mUrl);

mStream = mClient.GetStream();

int port = ((IPEndPoint)mClient.Client.RemoteEndPoint).Port;

if (port != 80)

host = host + ":" + port;

StringBuilder extraHeaders = new StringBuilder();

if (mHeaders != null)

{

foreach (KeyValuePair header in mHeaders)

extraHeaders.Append(header.Key + ": " + header.Value + "\r\n");

}

string request = "GET " + path + " HTTP/1.1\r\n" +

"Upgrade: WebSocket\r\n" +

"Connection: Upgrade\r\n" +

"Host: " + host + "\r\n" +

"Origin: " + origin + "\r\n" +

extraHeaders.ToString() + "\r\n";

byte[] sendBuffer = Encoding.UTF8.GetBytes(request);

mStream.Write(sendBuffer,sendBuffer.Length);

StreamReader reader = new StreamReader(mStream);

{

string header = reader.ReadLine();

if (!header.Equals("HTTP/1.1 101 Web Socket Protocol Handshake"))

throw new IOException("Invalid handshake response");

header = reader.ReadLine();

if (!header.Equals("Upgrade: WebSocket"))

throw new IOException("Invalid handshake response");

header = reader.ReadLine();

if (!header.Equals("Connection: Upgrade"))

throw new IOException("Invalid handshake response");

}

mHandshakeComplete = true;

}

public void Send(string str)

{

if (!mHandshakeComplete)

throw new InvalidOperationException("Handshake not complete");

byte[] sendBuffer = Encoding.UTF8.GetBytes(str);

mStream.WriteByte(0x00);

mStream.Write(sendBuffer,sendBuffer.Length);

mStream.WriteByte(0xff);

mStream.Flush();

}

public string Recv()

{

if (!mHandshakeComplete)

throw new InvalidOperationException("Handshake not complete");

StringBuilder recvBuffer = new StringBuilder();

BinaryReader reader = new BinaryReader(mStream);

byte b = reader.ReadByte();

if ((b & 0x80) == 0x80)

{

// Skip data frame

int len = 0;

do

{

b = (byte)(reader.ReadByte() & 0x7f);

len += b * 128;

} while ((b & 0x80) != 0x80);

for (int i = 0; i < len; i++)

reader.ReadByte();

}

while (true)

{

b = reader.ReadByte();

if (b == 0xff)

break;

recvBuffer.Append(b);

}

return recvBuffer.ToString();

}

public void Close()

{

mStream.Dispose();

mClient.Close();

mStream = null;

mClient = null;

}

private static TcpClient CreateSocket(Uri url)

{

string scheme = url.Scheme;

string host = url.DnsSafeHost;

int port = url.Port;

if (port <= 0)

{

if (scheme.Equals("wss"))

port = 443;

else if (scheme.Equals("ws"))

port = 80;

else

throw new ArgumentException("Unsupported scheme");

}

if (scheme.Equals("wss"))

throw new NotImplementedException("SSL support not implemented yet");

else

return new TcpClient(host,port);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值