WebSocket實現C#端和H5進行交互


C#服務器端的代碼

static void Main(string[] args)
        {
            //DataBase db = new DataBase();

            int id = 0;

            //Fleck
            var server = new WebSocketServer("ws://10.0.0.21:12345");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    socket.Send("hello");
                };

                socket.OnClose = () => Console.WriteLine("Close!");
                socket.OnMessage = message =>
                {

                    id = Convert.ToInt32(message);
                    Console.WriteLine(message);

                    SoundPlayer sp = null;


                    Console.WriteLine(message);


            //這邊寫自己的邏輯
////嘗試用websocket進行登錄 //db.reader = db.GetList("SELECT sing FROM sing WHERE id=" + message); //string namespaceName = Assembly.GetExecutingAssembly().GetName().Name.ToString(); //Assembly assembly = Assembly.GetExecutingAssembly(); //while (db.reader.Read()) //{ // System.Diagnostics.Process.Start(db.reader[0].ToString()); //} }; }); Console.ReadLine();

H5端代碼

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <table border="" cellspacing="" cellpadding="">
            <tr><th onclick="WebSocketTest('1')">Header</th></tr>
            <tr><th onclick="WebSocketTest('2')">Header</th></tr>
        </table>
    </body>
    <script>
        function WebSocketTest(str) {
            if("WebSocket" in window) {
                var ws = new WebSocket("ws://10.0.0.21:12345");
                ws.onopen = function() {
                    ws.send(str);
                    alert("數據發送中...");
                };
                ws.onmessage = function(evt) {
                    var received_msg = evt.data;
                    alert("數據已接收...");
                };
                ws.onclose = function() {
                    alert("連接已關閉...");
                };
            } else {
                alert("您的瀏覽器不支持 WebSocket!");
            }
        }
    </script>
    </script>

</html>

 

注意事項:

1.IP地址修改成自己的

2.H5部分用的是

WebSocketTest()方法 

 3.C#部分需要引入東西 去哪個Visual Studio中引入 Fleck


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM