由于某些原因,我无法从JavaScript客户端连接到WebSocket服务器。

我的服务器:

[ServiceContract(CallbackContract = typeof(IHelloCallback))]
public interface IHelloService
{
    [OperationContract(IsOneWay = true)]
    Task Hello(string msg);
}

[ServiceContract]
public interface IHelloCallback
{
    [OperationContract(IsOneWay = true)]
    Task OnHello(string msg);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class HelloService : IHelloService
{
    public async Task Hello(string msg)
    {
        var callback = OperationContext.Current.GetCallbackChannel<IHelloCallback>();
        await callback.OnHello(msg);
    }
}

class Program
{
    static void Main(string[] args)
    {
              ConfigurationManager.AppSettings
    ["aspnet:UseTaskFriendlySynchronizationContext"] = "true";

  var mapping = new System.ServiceModel.Configuration.ProtocolMappingElementCollection();
  mapping.Add(
    element: new ProtocolMappingElement(
      schemeType: "http",
      binding: "netHttpBinding",
      bindingConfiguration: "default"));
  mapping.Add(
    element: new ProtocolMappingElement(
      schemeType: "https",
      binding: "netHttpsBinding",
      bindingConfiguration: "default"));

  ServiceHost serviceHost = null;

  try {
    string addressStr = "http://localhost:27272/HelloService";

    var binding = new NetHttpBinding(
      securityMode: BasicHttpSecurityMode.None,
      reliableSessionEnabled: true);

    var addressUri = new Uri(uriString: addressStr);

    serviceHost = new ServiceHost(
      serviceType: typeof(HelloService),
      baseAddresses: addressUri);

    var endpoint = serviceHost.AddServiceEndpoint(
      implementedContract: typeof(IHelloService),
      binding: binding,
      address: addressUri);

    serviceHost.Open();

    Console.WriteLine(
      "WebSocketsServiceValues service is running, press any key to close...");
    Console.ReadKey();

  }
  catch (Exception ex) {
    Console.WriteLine(ex.ToString());
  }
  finally {
    serviceHost.Close();
  }
}
}


我的客户:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>WebSocket Chat</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
    <script type="text/javascript">
        var ws;
        $().ready(function () {
            $("#btnConnect").click(function () {
                $("#spanStatus").text("connecting");
                ws = new WebSocket("ws://localhost:27272/HelloService");
                ws.onopen = function () {
                    $("#spanStatus").text("connected");
                };
                ws.onmessage = function (evt) {
                    $("#spanStatus").text(evt.data);
                };
                ws.onerror = function (evt) {
                    $("#spanStatus").text(evt.message);
                };
                ws.onclose = function () {
                    $("#spanStatus").text("disconnected");
                };
            });
            $("#btnSend").click(function () {
                if (ws.readyState == WebSocket.OPEN) {
                    ws.send($("#textInput").val());
                }
                else {
                    $("#spanStatus").text("Connection is closed");
                }
            });
            $("#btnDisconnect").click(function () {
                ws.close();
            });
        });
    </script>
</head>
<body>
    <input type="button" value="Connect" id="btnConnect" />
    <input type="button" value="Disconnect" id="btnDisconnect" /><br />
    <input type="text" id="textInput" />
    <input type="button" value="Send" id="btnSend" /><br />
    <span id="spanStatus">(display)</span>
</body>
</html>

最佳答案

我确实注意到了一些有趣的事情。可以帮助您:
客户端发送服务器的消息如下所示:

升级:websocket
连接方式:升级
主机:localhost:27272
来源:null
语法:无缓存
Sec-WebSocket-Key:6hblahblahblah
Sec-WebSocket-Version:13 ---这很有趣
等等...


如果您使用Fiddler并将其切换到

秒WebSocket版本:13、7


或除13以外的任何数字

安全WebSocket版本:12


安全WebSocket版本:14


您会从服务器收到426响应,我认为这是进行协商的正确下一步。我对此进行了一些研究,并且您所使用的msdn api实际上是非文档的,而JavaScript api却是la脚的(您似乎无法在那里配置标头)。

07-24 09:47
查看更多