使用TCP与websocket服务器建立连接

时间:2018-01-27 11:19:15

标签: c# .net sockets tcp websocket

我尝试使用TCP连接到websocket服务器。 但是,我在做这件事时遇到了问题 - 来自服务器的空响应。 我在做什么。 首先,我建立了#34;握手"标题看起来像folows:

"GET /mqtt HTTP/1.1\r\n" + "Host: broker.mqttdashboard.com\r\n" +
    "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" +
    "Origin: broker.mqttdashboard.com\r\n\r\n";

接下来,我创建套接字并将标头发送到服务器:

var ips = Dns.GetHostEntry("broker.mqttdashboard.com");
        sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        sock.Connect(ips.AddressList[0], 8000);
sock.Send(Encoding.UTF8.GetBytes(header));
        var buf = new byte[4096];
        var rec = sock.Receive(buf);

        var response = Encoding.UTF8.GetString(buf, 0, rec);

"握手"是成功的,因为我得到了下一个标题作为回应:

HTTP/1.1 101 Web Socket Protocol Handshake
upgrade: websocket
connection: upgrade
websocket-origin: broker.mqttdashboard.com
websocket-location: ws://broker.mqttdashboard.com/mqtt

之后我无法连接。我正在构建下一个连接头:

"CONNECT clientId-nVqGddbrRK@broker.mqttdashboard.com:8000 HTTP/1.1\r\n" + "host: broker.mqttdashboard.com\r\n" +
            "\r\n";

我有空洞的回应。能不能指出我做错了什么。

0 个答案:

没有答案