您好!欢迎来到默认站点! 请登录 注册有礼
首页 新闻资讯 > 研发日志 > C#

c# Fleck WebSocket 通讯

2020-5-25 19:52:00 人评论

JavaScript 客户端 + C# WebSocket 服务端基于Fleck类库服务端WebSocketHelper管理类代码:using System;using System.Collections.Generic;using System.Linq;using System.Text;using Fleck;namespace Mvcms.Common.Net { /// <summary> /// WebSocket管理类 …

JavaScript 客户端 + C# WebSocket 服务端

基于Fleck类库

服务端WebSocketHelper管理类代码:

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

namespace Mvcms.Common.Net {
    /// <summary>
    /// WebSocket管理类
    /// </summary>
    public class WebSocketHelper {
        private static string ipaddress = "0.0.0.0";
        /// <summary>
        /// 设置或获取服务Ip地址
        /// </summary>
        public static string Ipaddress {
            get { return ipaddress; }
            set { ipaddress = value; }
        }
        private static int port = 7777;
        /// <summary>
        /// 设置或获取服务端口
        /// </summary>
        public static int Port {
            get { return port; }
            set { port = value; }
        }

        private static bool broadcast = false;
        /// <summary>
        /// 是否广播客户端消息到所有客户端
        /// </summary>
        public static bool Broadcast {
            get { return broadcast; }
            set { broadcast = value; }
        }

        /// <summary>
        /// WebSocket服务实例
        /// </summary>
        private static IWebSocketServer server = null;
        /// <summary>
        /// WebSocket客户端连接对象字典(key:客户端IP, value:客户端WebSocket连接对象)
        /// </summary>
        private static Dictionary<string, IWebSocketConnection> clients = new Dictionary<string, IWebSocketConnection>();

        private static Queue<string> messages = new Queue<string>();

        /// <summary>
        /// 从队列弹出一条客户端消息
        /// </summary>
        /// <returns></returns>
        public static string GetMessage(){
            return messages.Peek();
        }

        /// <summary>
        /// 创建WebSocket服务
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <param name="port"></param>
        public static void Open() {
            if (server != null) {
                return;
            }
            string location = string.Format("ws://{0}:{1}", ipaddress, port);
            server = new WebSocketServer(location);//创建服务
            //开始监听
            server.Start(socket => {
                socket.OnOpen = () => {//客户端连接建立事件
                    string ip = socket.ConnectionInfo.ClientIpAddress;
                    if (!clients.ContainsKey(ip)) {
                        clients.Add(ip, socket);
                    }
                };
                socket.OnClose = () => {//客户端连接关闭事件
                    string ip = socket.ConnectionInfo.ClientIpAddress;
                    if (clients.ContainsKey(ip)) {
                        clients.Remove(ip);
                    }
                };
                socket.OnMessage = message => {//接受客户端网页消息事件
                    messages.Enqueue(string.Format("{0} Receive form {1}:{2}",DateTime.Now, socket.ConnectionInfo.ClientIpAddress, message));
                    if (broadcast) {//广播消息到所有客户端
                        foreach (KeyValuePair<string, IWebSocketConnection> client in clients) {
                            client.Value.Send("Echo:" + message);
                        }
                    }
                };
            });
        }

        /// <summary>
        /// 关闭WebSocket服务
        /// </summary>
        /// <returns></returns>
        public static int Close() {
            if (server == null) {
                return -1;
            }
            int count = clients.Count;
            foreach (KeyValuePair<string, IWebSocketConnection> client in clients) {
                client.Value.Close();
            }
            server.Dispose();
            server = null;
            return count;
        }

        /// <summary>
        /// 发送内容到所有客户端
        /// </summary>
        /// <param name="content"></param>
        public static int Send(string content) {
            if (server == null) {
                return 0;
            }
            foreach (KeyValuePair<string, IWebSocketConnection> client in clients) {
                client.Value.Send(content);
            }
            return clients.Count;
        }

        /// <summary>
        /// 发送内容到指定客户端
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static bool Send(string ipaddress, string content) {
            if (server == null) {
                return false;
            }
            IWebSocketConnection socket;
            if (clients.TryGetValue(ipaddress, out socket)) {
                socket.Send(content);
                return true;
            } else {
                return false;
            }
        }
    }
}

服务端控制器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Text;
using Mvcms.Common;
using Mvcms.Common.Net;

namespace Mvcms.Web.Controllers.admin.application {
    public class websocketController : UI.Controllers.BaseManageController {
        // GET: /admin/websocket/
        public ActionResult Index() {
            ViewBag.ipaddress = RequestHelper.GetIP();
            ViewBag.port = WebSocketHelper.Port;
            WebSocketHelper.Open();
            WebSocketHelper.Broadcast = true;
            return View(GetViewName(ViewPathName));
        }
    }
}

客户端视图代码:

@model List<Mvcms.Common.Net.BaseDeviceReceive>
@using Mvcms.Common;
@{
    Layout = "~/Areas/admin/Views/Shared/_LayoutList.cshtml";
    ViewBag.Title = "设备搜索";
    Mvcms.Entities.sysconfig sysconfig = ViewData["sysConfig"] as Mvcms.Entities.sysconfig;
}
@section HeaderContent{
    <style>
        .content-box { position: relative; width:100%; margin-right: 5px; }
        .content-left { float: left; width: 230px; min-height: 640px; }
        .content-left dl dt{ width:60px; }
        .content-left dl dd { margin-left:65px; }
        .content-main dl dt { width:auto; }
        .content-main { margin-left: 235px; position: absolute; top: 0; min-width:640px; min-height: 640px; }
    </style>
    <script>
        var data = {
            ip: '@ViewBag.ipaddress',
            port: '@ViewBag.port',
            url: 'ws://@ViewBag.ipaddress:@ViewBag.port',
            socket: null
        };
        var that = this;
        $(function () {
            if ('WebSocket' in window) {
                UI.msg({ style: 'success', title: '当前浏览器支持WebSocket ☺' });
                createSocket();
            }
            else {
                UI.dialog({ style: 'error', content: '当前浏览器不支持WebSocket!' });
            }
        });

        function submitOpen(sender) {
            createSocket();
        }


        function createSocket() {
            var url = 'ws://' + $('#txtIP').val() + ':' + $('#txtPort').val();
            that.data.url = url;
            var ws = new WebSocket(url);
            that.data.socket = ws;
            ws.onopen = function (event) {
                console.log('opened: ' + url);
                ws.send('ok');
            };
            ws.onmessage = function (message) {
                console.log('receive: ' + message.data);
                $('#txtReceive').append('Receive: ' + message.data + '\n');
            };

            ws.onclose = function (event) {
                console.log('colse: ' + that.data.url);
                $('#txtReceive').append('Closed\n');
            }
            ws.onerror = function (error) {
                console.log('error: ' + JSON.stringify(error));
                $('#txtReceive').append('Error: ' + JSON.stringify(error) + '\n');
            }
        }

        function submitSend(sender) {
            var content = $('#txtSend').val();
            that.data.socket.send(content);
            console.log('send ' + content + ' to ', that.data.socket);
        }

        function cleanReceive(sender) {
            $('#txtReceive').empty();
        }
    </script>
}

<!--导航栏-->
<div class="location">
    <a href="javascript:history.back(-1);" class="back"><i class="iconfont icon-up"></i><span>返回上一页</span></a>
    <a href="../../center/index"><i class="iconfont icon-home"></i><span>首页</span></a>
    <i class="arrow iconfont icon-arrow-right"></i>
    <span>WebSocket客户端</span>
</div>
<div id="setPanel" class="set-right">
    <div class="info">
        <a href="javascript:help();"><i class="iconfont icon-help"></i></a>
    </div>
</div>
<!--/导航栏-->

<!--标签页头-->
<div id="floatHead" class="content-tab-wrap">
    <div class="content-tab">
        <div class="content-tab-ul-wrap">
            <ul>
                <li><a class="selected" href="javascript:;">WebSocket Client</a></li>
            </ul>
        </div>
    </div>
</div>
<!--/标签页头-->

<!--WebSocket调试-->
<div class="tab-content">
    <div class="content-box">
        <div class="content-left">
            <dl>
                <dt>目标地址</dt>
                <dd>
                    <input type="text" id="txtIP" class="input sub-input" value="@ViewBag.ipaddress" /></dd>
            </dl>
            <dl>
                <dt>目标端口</dt>
                <dd>
                    <input type="number" id="txtPort" class="input sub-input" value="@ViewBag.port" /></dd>
            </dl>
            <dl>
                <dt></dt>
                <dd>
                    <input type="button" class="input red small" onclick="submitOpen(this);" value="连接" />
                </dd>
            </dl>
        </div>
        <div class="content-main">
            <dl>
                <dt>发送内容</dt>
                <dd></dd>
            </dl>
            <textarea id="txtSend" class="input" rows="5" style="width: 100%;">@ViewBag.content</textarea>
            <dl>
                <dt>接收内容</dt>
                <dd style="text-align:right;">
                    <input type="button" class="input small blue" onclick="cleanReceive(this);" value="清空内容" />
                    <input type="button" class="input small red" onclick="submitSend(this);" value="发送内容" />
                </dd>
            </dl>
            
            <textarea id="txtReceive" rows="15" class="input" style="width: 100%; border: 1px solid #eee; font-size: 100%;"></textarea>
        </div>
    </div>
</div>
<!--/SebSocket调试-->

运行界面:

图片.png


相关资讯

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?
    会员登陆
    18004549898
    QQ
    Mvcms网站管理系统客服QQ:
    返回顶部