在 HTML5 和 C# Web 套接字通信之间

between html5 and C# web socket communication

本文关键字:套接字 通信 之间 Web HTML5      更新时间:2023-09-26

尝试使用此代码将字符串数据发送到Windows C#应用程序;

try {
    var ws = new WebSocket('ws://192.168.1.77:10048');
    ws.onopen = function () {
        ws.send("Sunucuya mesaj"); // I WANT TO SEND THIS MESSAGE TO SERVER!
    };
    ws.onclose = function () {
        alert('Bağlantı kapandı.');
    };
}
catch (e) {
    alert(e);
}

并尝试使用此代码从 Windows C# 应用程序获取数据;

static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8181));
serverSocket.Listen(128);
serverSocket.BeginAccept(null, 0, OnAccept, null);

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)
        {
            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 subA = SubArray<byte>(buffer, 0, i);
            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);
        }
    }
}

使用此代码,我可以在客户端和服务器之间进行通信,但我无法获得ws.send("Sunucuya mesaj"); 来自从客户端发送的服务器的消息。headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).子字符串(0, i);在此行中,您可以看到从服务器获取的标头;

获取/HTTP/1.1
升级:网络套接字
连接:升级
主机:192.168.1.77:8181
产地:http://localhost
Sec-WebSocket-Key: dHI34r7feV/Ar4G0/fONCg==
秒网套接字版本:13
Sec-WebSocket-Extensions: x-webkit-deflate-frame

如何从服务器端获取来自客户端的数据?

谢谢。。。

客户端和服务器之间的消息不是纯文本。 有关如何编码/解码消息的详细信息,请参阅协议规范的数据成帧部分。

您可以从

几个自由许可的开源 C# 服务器中获取示例。 如弗莱克