Websocket 服务器:永远不会调用 Web 套接字上的 onopen 函数 [英] Websocket server: onopen function on the web socket is never called

查看:12
本文介绍了Websocket 服务器:永远不会调用 Web 套接字上的 onopen 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个 C# 网络套接字服务器,但它给我带来了一些麻烦.我正在运行一个网络服务器(ASP.NET)来托管带有 javascript 的页面,而网络套接字服务器是作为 C# 控制台应用程序实现的.

I'm trying to implement a C# web socket server, but its giving me a few troubles. I'm running a webserver(ASP.NET) to host the page with the javascript and the web socket server is implemented as a C# console application.

我能够检测到来自客户端(运行 javascript 的 chrome)的连接尝试,并且还可以从客户端检索握手.但是客户端似乎不接受我发回的握手(网络套接字上的 onopen 函数从未被调用).

I'm able to detect the connection attempt from the client (chrome running the javascript) and also to retrieve the handshake from the client. But the client doesn't seem to accept the handshake I'm sending back (the onopen function on the web socket is never called).

我一直在阅读网络套接字协议 我看不出我做错了什么.这里有一些服务器代码:

I've been reading the The Web Socket protocol and I can't see what I'm doing wrong. Heres a bit of the server code:

Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8181);
listener.Bind(ep);
listener.Listen(100);
Console.WriteLine("Wainting for connection...");
Socket socketForClient = listener.Accept();
if (socketForClient.Connected)
{
    Console.WriteLine("Client connected");
    NetworkStream networkStream = new NetworkStream(socketForClient);
    System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
    System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);

    //read handshake from client:
    Console.WriteLine("HANDSHAKING...");
    char[] shake = new char[255];
    streamReader.Read(shake, 0, 255);

    string handshake =
       "HTTP/1.1 101 Web Socket Protocol Handshake
" +
       "Upgrade: WebSocket
" +
       "Connection: Upgrade
" +
       "WebSocket-Origin: http://localhost:8080
" +
       "WebSocket-Location: ws://localhost:8181
" +
       "
";

    streamWriter.Write(handshake);
    streamWriter.Flush();

我运行到端口 8080 上的 Web 服务器和端口 8181 上的 Web 套接字服务器,两者都在我的本地主机上.

I'm running to web server on port 8080 and the web socket server on port 8181, both on my localhost.

我尝试以不同的编码(ASCII、字节和十六进制)发送握手,但这似乎没有什么区别.连接永远不会完全建立.javascript 看起来像这样:

I've tried sending the handshake in different encodings (ASCII, bytes and Hex) but this doesn't seem to make a difference. The connection is never fully established. The javascript looks like this:

var ws;
var host = 'ws://localhost:8181';
debug("Connecting to " + host + " ...");
try {
 ws = new WebSocket(host);
} catch (err) {
 debug(err, 'error');
}
ws.onopen = function () {
 debug("connected...", 'success');
};
ws.onclose = function () {
 debug("Socket closed!", 'error');
};
ws.onmessage = function (evt) {
 debug('response: ' + evt, 'response');
};

我猜测错误出在 C# 服务器上,因为 chrome 正在按原样发送信息,但正如所说的那样,onopen 函数从未被调用.

I'm guessing that the error lies in the C# server as chrome is sending the information as it should, but as a said the onopen function is never called.

我的问题简而言之:你们有没有人做到过这一点——如果是,你是怎么做到的?原因:您是否在代码中看到任何明显错误(希望不要问太多)

So my question in short: Has any of you ever accomplished this - and if yes, how did you do it? And of cause: Do you see any apparent errors in the code (hope thats not to much to ask)

推荐答案

可能是编码问题.这是我写的一个工作的 C# 服务器:

Probably it's an encoding issue. Here's a working C# server I wrote:

class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Loopback, 8181);
        listener.Start();
        using (var client = listener.AcceptTcpClient())
        using (var stream = client.GetStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        {
            writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            writer.WriteLine("Upgrade: WebSocket");
            writer.WriteLine("Connection: Upgrade");
            writer.WriteLine("WebSocket-Origin: http://localhost:8080");
            writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
            writer.WriteLine("");
        }
        listener.Stop();
    }
}

以及托管在localhost:8080上的相应客户端:

And the corresponding client hosted on localhost:8080:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <script type="text/javascript">
      var socket = new WebSocket('ws://localhost:8181/websession');
      socket.onopen = function() {
        alert('handshake successfully established. May send data now...');
      };
      socket.onclose = function() {
        alert('connection closed');
      };
    </script>
  </head>
  <body>
  </body>
</html>

这个例子只建立了握手.您需要调整服务器,以便在建立握手后继续接受数据.

This example only establishes the handshake. You will need to tweak the server in order to continue accepting data once the handshake has been established.

这篇关于Websocket 服务器:永远不会调用 Web 套接字上的 onopen 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆