Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在WebSocket中发送消息_C#_Websocket - Fatal编程技术网

C# 如何在WebSocket中发送消息

C# 如何在WebSocket中发送消息,c#,websocket,C#,Websocket,我使用了一个简单的WebSocket服务器,其中web客户端发送消息Hello Wordld,然后服务器响应客户端并发送Hello World。但我想从服务器上获取数据,客户端将在网页上打印日期。我做错了什么?你能帮我吗 namespace WebSocket { class Program { static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolT

我使用了一个简单的WebSocket服务器,其中web客户端发送消息Hello Wordld,然后服务器响应客户端并发送Hello World。但我想从服务器上获取数据,客户端将在网页上打印日期。我做错了什么?你能帮我吗

namespace WebSocket
 {
class Program
{
    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.BeginAccept(null, 0, OnAccept, null);
        Console.Read();
    }

    private static void OnAccept(IAsyncResult result)
    {
        byte[] buffer = new byte[1024];
        try
        {
            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-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 time = DateTime.Now.ToString();

                int length = time.Length;

                var Data = Encoding.UTF8.GetBytes(time);

                buffer = Data;


                var subA = SubArray<byte>(buffer, 0, length);
                client.Send(subA);
                Thread.Sleep(10000);//wait for message to be send


            }
        }
        catch (SocketException exception)
        {
            throw exception;
        }
        finally
        {
            if (serverSocket != null && serverSocket.IsBound)
            {
                serverSocket.BeginAccept(null, 0, OnAccept, null);
            }
        }
    }

    public static T[] SubArray<T>(T[] data, int index, int length)
    {
        T[] result = new T[length];
        Array.Copy(data, index, result, 0, length);
        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));
    }
}
并更改

                var subA = SubArray<byte>(buffer, 0, length);

之后一切都是工作,但它只发送Hello World,但我想发送一个时间和日期。我怎么能做到?请帮帮我,你应该看看。这个开源库可以依赖于web套接字和许多其他工具,但我需要不使用任何工具来实现它libraries@SteveB:只要服务器上的应用程序位于虚拟目录中,Signal就会失败。。。
 var time = DateTime.Now.ToString();
 int length = time.Length;
 var Data = Encoding.UTF8.GetBytes(time);
  buffer = Data;
                var subA = SubArray<byte>(buffer, 0, length);