我正在使用c#编写自定义Websocket服务器。根据{{3}} mozilla指南,我写了一些代码。现在,我成功地握手并从客户端接收消息,并且所有消息都在Chrome上运行,但是当我尝试从FireFox上的服务器发送消息时,我收到控制台错误“与ws:// localhost:80的连接为页面加载时中断”。我正在使用来自this的算法和来自this page的客户端发送编码消息,发送编码消息。您可以在websocket echo test
上找到整个项目我尝试发送不编码的字节,并在每次发送消息时重新打开websoket连接)。
如您所见,服务器会自动向客户端发送消息“ Hello”。 进程功能(每个客户端有新线程):
public void Process()
{
try
{
Stream = _client.GetStream();
HandShake();
while (true)
{
while (_client.Available < 3)
{
}
Byte[] bytes = new Byte[_client.Available];
Stream.Read(bytes, 0, bytes.Length);
var message = GetMessage(bytes);
if (_webSocketConverter.IsClosing(bytes[0]))
{
break;
}
message = GetMessage(bytes);
SendMessageFromServer("Hello");
}
}
catch (Exception ex)
{
throw ex;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
finally
{
_server.RemoveConnection(this._userInfo.Id);
Console.WriteLine("Client {0} disconnected from the server", this._userInfo.Id);
Close();
}
}
SendMessage函数(EncodeMessage-上面链接中的算法,可以很好地与chrome配合使用)
private void SendMessageFromServer(string message)
{
Byte[] messageByte = _webSocketConverter.EncodeMessage(message);
Stream.Write(messageByte);
}
好像服务器有问题,因为websocket.org/echo使用Firefox。
答案 0 :(得分:0)
可能的解决方案可能与Firefox Connection
标头有关。
通过比较Chrome和Firefox上的WebSocket连接请求,可以发现Firefox上的Connection
标头是"keep-alive, Upgrade"
而不是"Upgrade"
(在Chrome上)。
可能的解决方案是测试标头中是否存在Upgrade
(不区分大小写),而不是测试总标头是否相等。
Chrome(在我的计算机上)对WebSocket的完整请求如下:
Read: GET /HTTP/1.1
Host: localhost:3000
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://localhost:3000
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Sec-WebSocket-Key: NmFGZCcMdiNlXoW/R+F0lw==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
在Firefox上完整的WebSocket请求如下:
GET / HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Sec-WebSocket-Version: 13
Origin: http://localhost:3000
Sec-WebSocket-Extensions: permessage-deflate
Sec-WebSocket-Key: QU6J0KFZjDA/OgVSATpYDg==
Connection: keep-alive, Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
答案 1 :(得分:0)
谢谢大家的回答。发现问题!这是我的编码功能(wesocketconverter.cs)。我将格式化的数组初始化为raw array.length +10。因此,我得到了8个额外的空字节。当多余的字节为偶数时,Chrome处理它,但Firefox则不然。迟早它将在chrome上停止工作。