一尘不染

Websocket服务器:永远不会调用Web套接字上的onopen函数

c#

我正在尝试实现C#Web套接字服务器,但它给我带来了一些麻烦。我正在运行Web服务器(ASP.NET),以使用javascript托管页面,并且Web套接字服务器已实现为C#控制台应用程序。

我能够检测到来自客户端的连接尝试(运行javascript的Chrome浏览器),还可以从客户端检索握手。但是客户端似乎不接受我发回的握手信号(onopen从不调用Web套接字上的函数)。

我一直在阅读Web套接字协议,但看不到我在做什么错。以下是服务器代码:

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\r\n" +
       "Upgrade: WebSocket\r\n" +
       "Connection: Upgrade\r\n" +
       "WebSocket-Origin: http://localhost:8080\r\n" +
       "WebSocket-Location: ws://localhost:8181\r\n" +
       "\r\n";

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

我正在本地主机上运行端口8080上的Web服务器和端口8181上的Web套接字服务器。

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

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,从未调用过该函数。

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


阅读 2543

收藏
2020-05-19

共1个答案

一尘不染

可能是编码问题。这是我编写的可运行的C#服务器:

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

<!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>

本示例仅建立握手。建立握手后,您将需要调整服务器以继续接受数据。

2020-05-19