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

WebSocket实现C#端和H5进行交互

上一篇:k8s获取apiversion下面的对应可用资源


下一篇:【windows】ping对方ip端口