我正在尝试实现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,从未调用过该函数。简而言之,我的问题是: 你们中的任何人都做到过吗?如果是,您是如何做到的?原因:在代码中是否看到任何明显的错误(希望不要问太多)
3 回答
- 3 回答
- 0 关注
- 1714 浏览
添加回答
举报
0/150
提交
取消