将JavaScript WebSocket连接到C winsock

时间:2016-12-20 09:38:49

标签: javascript c++ websocket server winsock

我设法将我的JavaScript客户端连接到C ++服务器(我使用winsock),服务器收到HTTP标头,但之后我无法发送或接收任何其他内容。 服务器发送消息(send返回发送的字节数),但客户端没有任何内容。

客户端:JavaScript



function WebSocketTest()
{
  if ("WebSocket" in window)
  {
    var ws = new WebSocket("ws://192.168.43.205:80");

    ws.onopen = function()
    {
      ws.send("Message to send");//this doesn't work
    };

    ws.onmessage = function (evt) 
    { 
      var received_msg = evt.data;
      alert("Message is received...");
      document.getElementById("message").innerHTML += received_msg;
    };

    ws.onclose = function()
    { 
      alert("Connection is closed..."); 
    };

    ws.onerror = function(error){
      alert('Error detected: ' + error);
    }
  }

  else
  {
    // The browser doesn't support WebSocket
    alert("WebSocket NOT supported by your Browser!");
  }
}




服务器:C / C ++

#include <stdio.h>
#include "winsock2.h"
#include <iostream>
#include <string>

#pragma comment(lib, "Ws2_32.lib")
#define _WINSOCK_DEPRECATED_NO_WARNINGS

using namespace std;

void main() {
    int size;
    char buffer[1024];

    WSADATA wsaData;
    sockaddr_in service;
    SOCKET ListenSocket, AcceptSocket;

    service.sin_family = AF_INET;
    service.sin_addr.s_addr = INADDR_ANY;
    service.sin_port = htons(10011);

    WSAStartup(MAKEWORD(2, 2), &wsaData);
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    bind(ListenSocket, (SOCKADDR*)&service, sizeof(service));
    listen(ListenSocket, SOMAXCONN);

    AcceptSocket = accept(ListenSocket, NULL, NULL);
    cout << "Client connected.\n";

    size = recv(AcceptSocket, buffer, 1024, 0);
    string msg(buffer, size);
    /*
    msg contains this:
        GET / HTTP/1.1
        Host: 172.16.199.150:10011
        Connection: Upgrade
        Pragma: no-cache
        Cache-Control: no-cache
        Upgrade: websocket
        Origin: http://localhost
        Sec-WebSocket-Version: 13
        User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
        Accept-Encoding: gzip, deflate, sdch
        Accept-Language: en-US,en;q=0.8,hu;q=0.6
        Sec-WebSocket-Key: 34qTtPYjnRJheHKQowePRg==
        Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
    */

    string abc = "abc";
    auto cmsg = abc.c_str();
    size = send(AcceptSocket, cmsg, abc.size(), 0);
    // size == 3, which means send was successful, but client doesn't receive anything

    // hangs here, even tho client sent a message
    size = recv(AcceptSocket, buffer, 1024, 0);
}

1 个答案:

答案 0 :(得分:2)

webSocket连接使用整个连接方案及其自己的数据格式(例如,它是自己的协议)。要接收webSocket连接,您必须支持整个webSocket协议,包括HTTP连接方案,安全协商和数据帧格式。

由于许多语言都有许多预先编写的实现,因此大多数人将获得并使用现有的webSocket服务器实现,而不是从头开始重写它。

您可以在该文章中查看Writing webSocket servers所需内容的概述。