C#与html实现WebSocket交互,制作ktv手机点歌

C#端代码

 1 static void Main(string[] args)
 2         {
 3             int id = 0;
 4             //Fleck
 5             //自己本地的ipv4地址
 6             var server = new WebSocketServer("ws://10.0.0.21:12345");
 7             server.Start(socket =>
 8             {
 9                 socket.OnOpen = () =>
10                 {
11                     Console.WriteLine("Open!");
12                     socket.Send("hello");
13                 };
14 
15                 socket.OnClose = () => Console.WriteLine("Close!");
16                 socket.OnMessage = message =>
17                 {
18                     id = Convert.ToInt32(message);
19                     Console.WriteLine(message);
20                     SoundPlayer sp = null;
21                     Console.WriteLine(message);
22             //这边写自己的逻辑
23                 };
24             });
25 
26             Console.ReadLine();

H5端代码

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <table  cellspacing="" cellpadding="">
 9             <tr><th onclick="WebSocketTest('1')">Header</th></tr>
10             <tr><th onclick="WebSocketTest('2')">Header</th></tr>
11         </table>
12     </body>
13     <script>
14         function WebSocketTest(str) {
15             if("WebSocket" in window) {
16                 var ws = new WebSocket("ws://10.0.0.21:12345");
17                 ws.onopen = function() {
18                     ws.send(str);
19                     alert("数据发送中...");
20                 };
21                 ws.onmessage = function(evt) {
22                     var received_msg = evt.data;
23                     alert("数据已接收...");
24                 };
25                 ws.onclose = function() {
26                     alert("连接已关闭...");
27                 };
28             } else {
29                 alert("您的浏览器不支持 WebSocket!");
30             }
31         }
32     </script>
33     </script>
34 
35 </html>

注意:

1:ip地址为自己当前网络的ipv4地址;

2:c#需要添加应用,去搜索 Fleck

3:h5调用websocket()方法;