简体   繁体   English

C#WebSocket服务器未触发html5中的onmessage事件

[英]C# websocket server not firing the onmessage event in html5

Perhaps I badly need a hand now. 也许我现在急需帮助。

I am currently having a problem regarding websocket server using c# and HTML5. 我目前在使用c#和HTML5的websocket服务器方面遇到问题。 It is not firing my onmessage() event in html5. 它没有触发html5中的onmessage()事件。 It opens the socket connection and triggers the onopen() event. 它打开套接字连接并触发onopen()事件。 But, once a connection is established, it continues to close the connection. 但是,一旦建立连接,它将继续关闭连接。 Here's my simple code: 这是我的简单代码:

SERVER (c#): 服务器(c#):

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        public Socket ListenerSocker { get; private set; }
        static IPEndPoint ipLocal;
        static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

        static void Main(string[] args)
        {
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
            //serverSocket.Listen(128);
            serverSocket.Listen(200);
            serverSocket.BeginAccept(null, 0, OnAccept, null);

            Console.Read();
        }


        private static void OnClientConnect()
        {

            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }







        private static void OnAccept(IAsyncResult result)
        {
            byte[] buffer = new byte[1024];

            Socket client = null;
            string headerResponse = "";
            if (serverSocket != null && serverSocket.IsBound)
            {
                client = serverSocket.EndAccept(result);
                var i = client.Receive(buffer);
                headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                // write received data to the console
                Console.WriteLine(headerResponse);

            }
            if (client != null)
            {
                /* Handshaking and managing ClientSocket */

                var key = headerResponse.Replace("ey:", "`")
                          .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                          .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                          .Trim();

                // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                var test1 = AcceptKey(ref key);

                var newLine = "\r\n";

                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                     + "Sec-WebSocket-Key: " + test1 + newLine + newLine
                     + "Sec-WebSocket-Key: " + test1 + newLine + newLine
                    //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                    //+ "Sec-WebSocket-Version: 13" + newLine
                     ;

                // which one should I use? none of them fires the onopen method
                client.Send(System.Text.Encoding.UTF8.GetBytes(response));

                var i = client.Receive(buffer); // wait for client to send a message

                // once the message is received decode it in different formats
                Console.WriteLine(Convert.ToBase64String(buffer).Substring(0, i));
                /*
                Console.WriteLine("\n\nPress enter to send data to client");
                Console.Read();
                */
                var subA = SubArray<byte>(buffer, 0, i);
                Console.WriteLine("***SUBA****:"+subA);
                Console.WriteLine("TEST");
                client.Send(subA);

                // Thread.Sleep(10000);//wait for message to be send

                // OnClientConnect();
            }
        }

        public static T[] SubArray<T>(T[] data, int index, int length)
        {
            T[] result = new T[length];
            Array.Copy(data, index, result, 0, length);
            Console.WriteLine(result);
            return result;
        }

        private static string AcceptKey(ref string key)
        {
            string longKey = key + guid;
            byte[] hashBytes = ComputeHash(longKey);
            return Convert.ToBase64String(hashBytes);
        }

        static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        private static byte[] ComputeHash(string str)
        {
            return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
        }
    }
}

CLIENT (HTML5): 客户(HTML5):

<!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">
        function connect() {
            var ws = new WebSocket("ws://localhost:8080");
            console.log(ws);
            ws.onopen = function () {
                alert("About to send data");
                ws.send("test"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
                alert("Message sent!");
            };

            ws.onmessage = function (evt) {
                alert("About to receive data");
                var received_msg = evt.data;
                alert("Message received = "+received_msg);
            };
            ws.onclose = function () {
                // websocket is closed.
                alert("Connection is closed...");
            };
        };

        function send(){
        }


    </script>
</head>
<body style="font-size:xx-large" >
    <div>
    <a href="#" onclick="connect()">Click here to start</a></div>

</body>
</html>

I can get this: 我可以得到这个:

 alert("About to send data");

and this: 和这个:

alert("Message sent!");

but after that, the connection closes. 但是之后,连接关闭。 I could also check that the server receives data from client. 我还可以检查服务器是否从客户端接收数据。 The thing is, once I send data from server to client, for me to be able to return what the client has given me, the connection suddenly closes. 关键是,一旦我从服务器向客户端发送数据,我就能够返回客户端给我的内容,连接突然关闭。 What could possibly be the problem? 可能是什么问题?

Websocket messages are not plain text; Websocket消息不是纯文本。 they need to have a simple framing protocol applied 他们需要应用简单的框架协议

Framing rules differ slightly for client->server and server->client messages. 客户端->服务器和服务器->客户端消息的框架规则略有不同。 I imagine the client is closing its connection when you try to echo its message without applying the different framing. 我想象当您尝试不应用其他框架而回显其消息时,客户端正在关闭其连接。

See the data framing section of RFC6455 for how to decode/encode messages. 有关如何解码/编码消息,请参见RFC6455的数据成帧部分 Or, if you're using .NET4.5, you could consider using System.Net.WebSockets instead of writing your own server. 或者,如果您使用的是.NET4.5,则可以考虑使用System.Net.WebSockets,而不是编写自己的服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM