using Fleck; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebSocketTest.DAL { public class TestSocket { private string msg = "默认信息"; public void socketServer() { string serverIP = 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)); }; }); } 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; } } }
配置文件部分
webapi代码如下
[RoutePrefix("api/server")] public class ValuesController : ApiController { [HttpGet,Route("getmsg")] public void getmsg() { TestSocket t = new TestSocket();//调用websocket工具类 t.socketServer(); } }
一般处理程序代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WebSocketTest.DAL; namespace WebSocketTest { /// /// test 的摘要说明 /// public class test : IHttpHandler { public void ProcessRequest(HttpContext context) { TestSocket t = new TestSocket(); t.socketServer(); } public bool IsReusable { get { return false; } } } }