c#--Fleck WebSocket使用 (C#版Websocket实例)

推荐几篇文章:
WebSocket 实战
C#版Websocket实例
C#工作总结(一):Fleck的WebSocket使用

1.服务端代码

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

namespace WebSocketTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //第一步:为当前项目添加 nutget引用。 工具---nutget包管理器--管理解决方案的nutget程序包
            //第一步:为当前项目添加 nutget引用。 工具---nutget包管理器--管理解决方案的nutget程序包
            //第一步:为当前项目添加 nutget引用。 工具---nutget包管理器--管理解决方案的nutget程序包

            //注意:使用实例2之前,先将实例1模块代码注释掉
            //注意:使用实例2之前,先将实例1模块代码注释掉
            //注意:使用实例2之前,先将实例1模块代码注释掉
            //注意:使用实例2之前,先将实例1模块代码注释掉
            //注意:使用实例2之前,先将实例1模块代码注释掉
            #region 实例2
            Console.WriteLine(DateTime.Now.ToString() + "   | 实例2 使用说明:");
            Console.WriteLine("1.先启动本程序,在打开实例2页面建立连接。");
            Console.WriteLine("2.注意:本程序可以接收任意次数的客户端信息,本程序也可以向客户端发送任意次数的消息");

            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0:7181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("与客户端已经连接上 Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("与客户端已经断开连接 Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send("客户端 Echo: " + message));
                };
            });


            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send("服务端: " + input);
                }
                input = Console.ReadLine();
            }

            #endregion




            //注意:使用实例1之前,先将实例2模块代码注释掉
            //注意:使用实例1之前,先将实例2模块代码注释掉
            //注意:使用实例1之前,先将实例2模块代码注释掉
            //注意:使用实例1之前,先将实例2模块代码注释掉
            //注意:使用实例1之前,先将实例2模块代码注释掉
            #region 实例1

            //Console.WriteLine(DateTime.Now.ToString() + "   | 实例1 使用说明:");
            //Console.WriteLine("1.先启动本程序,在打开实例1页面建立连接。");
            //Console.WriteLine("2.注意:本程序可以接收任意次数的客户端信息,但是本程序只能向客户端发送一次信息,然后本程序自动关闭。");

            ////客户端url以及其对应的Socket对象字典
            //IDictionary<string, IWebSocketConnection> dic_Sockets = new Dictionary<string, IWebSocketConnection>();
            ////创建

            //WebSocketServer server = new WebSocketServer("ws://0.0.0.0:30000");//监听所有的的地址
            ////出错后进行重启
            //server.RestartAfterListenError = true;

            ////开始监听
            //server.Start(socket =>
            //{
            //    socket.OnOpen = () =>   //连接建立事件
            //    {
            //        //获取客户端网页的url
            //        string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
            //        dic_Sockets.Add(clientUrl, socket);
            //        Console.WriteLine(DateTime.Now.ToString() + "|服务器:和客户端网页:" + clientUrl + " 建立WebSock连接!");
            //    };
            //    socket.OnClose = () =>  //连接关闭事件
            //    {
            //        string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
            //        //如果存在这个客户端,那么对这个socket进行移除
            //        if (dic_Sockets.ContainsKey(clientUrl))
            //        {
            //            //注:Fleck中有释放
            //            //关闭对象连接 
            //            //if (dic_Sockets[clientUrl] != null)
            //            //{
            //            //dic_Sockets[clientUrl].Close();
            //            //}
            //            dic_Sockets.Remove(clientUrl);
            //        }
            //        Console.WriteLine(DateTime.Now.ToString() + "|服务器:和客户端网页:" + clientUrl + " 断开WebSock连接!");
            //    };
            //    socket.OnMessage = message =>  //接受客户端网页消息事件
            //    {
            //        string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
            //        Console.WriteLine(DateTime.Now.ToString() + "|服务器:【收到】来客户端网页:" + clientUrl + "的信息:\n" + message);
            //    };
            //});

            //string userInput=Console.ReadLine();
            //foreach (var item in dic_Sockets.Values)
            //{
            //    if (item.IsAvailable == true)
            //    {
            //        item.Send("客户端:【收到】来服务端控制台程序:" + DateTime.Now.ToString()+"      ,服务端内容:   "+ userInput);
            //    }
            //}
            //Console.ReadLine();

            ////关闭与客户端的所有的连接
            //foreach (var item in dic_Sockets.Values)
            //{
            //    if (item != null)
            //    {
            //        item.Close();
            //    }
            //}

            //Console.ReadKey();

            #endregion
        }
    }
}

.
.
.

实例2页面代码

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>websocket client</title>
    <script type="text/javascript">
        var start = function () {
            var inc = document.getElementById('incomming');
            var wsImpl = window.WebSocket || window.MozWebSocket;
            var form = document.getElementById('sendForm');
            var input = document.getElementById('sendText');

            inc.innerHTML += "等待连接服务端 connecting to server ..<br/>";

            // create a new websocket and connect
            window.ws = new wsImpl('ws://localhost:7181/');

            // when data is comming from the server, this metod is called
            ws.onmessage = function (evt) {
                inc.innerHTML += evt.data + '<br/>';
            };

            // when the connection is established, this method is called
            ws.onopen = function () {
                inc.innerHTML += '与服务端已经连接上.. connection open<br/>';
            };

            // when the connection is closed, this method is called
            ws.onclose = function () {
                inc.innerHTML += '与服务端已经断开连接.. connection closed<br/>';
            }

            form.addEventListener('submit', function (e) {
                e.preventDefault();
                var val = input.value;
                ws.send(val);
                input.value = "";
            });

        }
        window.onload = start;
    </script>
</head>
<body>
    <a href="https://www.cnblogs.com/cjm123/p/9674506.html" target="_blank">C#版Websocket实例---原文链接</a>
    <a href="http://www.ibm.com/developerworks/cn/java/j-lo-WebSocket/" target="_blank">参考资料(介绍的非常详细全面,推荐)</a>
    <form id="sendForm">
        <input id="sendText" placeholder="输入消息,回车发送" />
    </form>
    <pre id="incomming"></pre>
</body>
</html>

.
.
.

实例1页面代码

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>WebSocket测试</title>
    <style>
        .div1 {
            height: 200px;
            width: 300px;
            border: 1px solid blue;
            margin: auto;
        }

        h4 {
            margin: auto;
        }
    </style>
    <script>
        var webSocket = {};
        //调用创建websockt方法
        CreateWebSocket();


        //创建websockt
        function CreateWebSocket() {
            webSocket = new WebSocket("ws://127.0.0.1:30000");
            webSocket.onopen = WebSokectOnOpen;
            webSocket.onmessage = WebSocketOnMessage;
            webSocket.onclose = WebSocketOnClose;
        };

        //建立连接事件
        function WebSokectOnOpen() {
            alert("已经打开连接!");
            webSocket.Send("WebSocketCreate Success!");
        };

        //监听事件
        function WebSocketOnMessage(event) {
            //监听来自客户端的数据
            alert(event.data);
        };

        function WebSocketOnClose() {
            //监听来自客户端的数据
            alert('和服务器断开连接');
        };

        //发送事件
        function WebSocketSendMsg() {
            //获取text中的值
            var text = document.getElementById("Text1").value;
            //发送到服务器
            webSocket.send(text);
        };
    </script>
</head>
<body οnlοad="CreateWebSocket()">
    <div class="div1">
        <a href="https://blog.csdn.net/ZslLoveMiwa/article/details/80247739" target="_blank">C#工作总结(一):Fleck的WebSocket使用--原文链接</a>
        <h4>CSDN博客</h4>
        <h4>By:LoveMiw</h4>
        <input type="text" id="Text1" />
        <input type="button" onclick="WebSocketSendMsg()" value="发送数据" />
    </div>
</body>
</html>
发布了36 篇原创文章 · 获赞 10 · 访问量 2825

猜你喜欢

转载自blog.csdn.net/VIP_CR/article/details/104798857