C# WebSocket 服务端接收并返回消息给客户端js

接手一个小项目,要求在页面控制罗茨泵的开启关闭。采用WebSocket传递消息,临时做个demo来测试场景。
1、首先写js中的部分代码:

    //通讯“套接字”
    var socket;
    switchLCBFun();
    function switchLCBFun() {
        //var host = "ws://" + $("#HFCtrlIP").val() + ":" + $("#HFCtrlPort").val() + "/";
        var host = "ws://xx.xx.xx.xx:8088/";//测试地址(服务器端地址)
        socket = new WebSocket(host);
        try {

            socket.onopen = function (msg) {
                alert("控制端连接成功!");
            };

            socket.onmessage = function (msg) {
                if (typeof msg.data == "string") {
                    alert("服务端返回消息" + msg.data);
                    onmessageAfter(msg.data);//自定义后续函数,不进行展示
                }
                else {
                    alert("非文本消息");
                }
            };

            socket.onclose = function (msg) {
                socket = null;
                alert("请开启控制端服务!开启后刷新重试否则影响罗茨泵远程控制!")
            };
        }
        catch (ex) {
            log(ex);
        }
    }
     //调用函数向服务端发送数据
    function switch_Send(commade) {

        var msgSend = commade + '\0';
        socket.send(msgSend);
        alert("正在执行操作,请稍等");
    }

2、服务端是个测试demo,创建一个控制台应用程序
在Program.cs文件中添加测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Fleck;

namespace ConsoleAppWebSocketTest
{
    class Program
    {
        private static string url = "";

        static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var server = new WebSocketServer("ws://xx.xx.xx.xx:8088/"); //服务端自己的IP和端口
            int clientPort = 0;
            string clientAddress = "";
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    clientPort = socket.ConnectionInfo.ClientPort;
                    clientAddress = socket.ConnectionInfo.ClientIpAddress;
                    Console.WriteLine("Open!");
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    url = "ws://"+ clientAddress +":"+ Convert.ToString(clientPort);
                    Console.WriteLine("客户端目标地址" + url);
                    Console.WriteLine("发送信息:罗茨泵开启");
                    Thread.Sleep(30000);
                    socket.Send("罗茨泵开启");
                    Console.WriteLine("发送成功!"); 
                };
            });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                input = Console.ReadLine();
            }
        }
    }
}

其中Fleck包可以在NUGET中下载或在网址:https://github.com/statianzo/Fleck中下载。
一个简单的websocket通信demo就完成了。

你可能感兴趣的:(C#,c#,websocket,js)