using Fleck; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WIDESEA.Common.ChatHub { public class WebSocketRover { public static string msg = "默认信息"; public void socketServer() { string serverIP = "ws://127.0.0.1:8099"; //System.Configuration.ConfigurationManager.AppSettings["serverIP"]; var allSockets = new List(); var server = new WebSocketServer(serverIP); server.Start(socket =>//服务开始 { socket.OnOpen = () => { Console.WriteLine("Open!"); allSockets.Add(socket); }; socket.OnClose = () => { Console.WriteLine("Close!"); allSockets.Remove(socket); }; socket.OnMessage = message => { //客户端交互的消息 System.Timers.Timer t = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为10000毫秒; t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件; t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件; allSockets.ToList().ForEach(s => s.Send("Echo: " + msg)); Console.WriteLine("here === "); }; }); } public void theout(object source, System.Timers.ElapsedEventArgs e) { msg = GetRandomString(); } /// ///生成随机字符串 --用于测试随机发送 /// ///目标字符串的长度 ///是否包含数字,1=包含,默认为包含 ///是否包含小写字母,1=包含,默认为包含 ///是否包含大写字母,1=包含,默认为包含 ///是否包含特殊字符,1=包含,默认为不包含 ///要包含的自定义字符,直接输入要包含的字符列表 ///指定长度的随机字符串 public static string GetRandomString() { byte[] b = new byte[4]; new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b); Random r = new Random(BitConverter.ToInt32(b, 0)); string s = null, str = ""; str += "我们都有一个家abcdefghijklmnopqrstuvwxyz123456789"; for (int i = 0; i < 15; i++) { s += str.Substring(r.Next(0, str.Length - 1), 1); } return s; } } }