c# - html5和C#之间的web socket通信

标签 c# javascript html sockets websocket

尝试使用此代码将字符串数据发送到 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)).Substring(0, i); 在这一行中,您可以看到从服务器获取的 header ;

GET/HTTP/1.1
升级:websocket
连接:升级
主机:192.168.1.77:8181
来源:http://localhost
Sec-WebSocket- key :dHI34r7feV/Ar4G0/fONCg==
Sec-WebSocket-版本:13
Sec-WebSocket-Extensions:x-webkit-deflate-frame

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

谢谢...

最佳答案

客户端和服务器之间的消息不是纯文本。请参阅data framing协议(protocol)规范部分了解如何编码/解码消息的详细信息。

有几个自由许可的开源 C# 服务器可供您引用。如Fleck

关于c# - html5和C#之间的web socket通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11915309/

相关文章:

c# - 空引用异常(从 mysql 下载 BLOB 文件)

javascript - 将值输入文本字段

javascript - 验证功能不起作用

HTML 视频自动播放不起作用

c# - 如何在 UWP 中创建 MapIcon 事件?

c# - 如何在 iTextSharp PDF Stamper 中使用 UTF-8 编码?

php - 通过 POST 将数组从 Javascript 传递到 PHP

html - 在 Internet Explorer 中,输入字段比选择框长几个像素;我怎样才能使它们的长度相同?

javascript - 如何将可拖动对象的移动限制在一个区域?

c# - newtonsoft.json 的两个依赖版本