本實例可通過web網頁端進行測試,下面直接上代碼。
首先要在NuGet導入“Fleck”包,需 .NET Framework 4.5及以上。
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Fleck.Samples.ConsoleApp { class Server { static void Main() { FleckLog.Level = LogLevel.Debug; var allSockets = new List<IWebSocketConnection>(); var server = new WebSocketServer("ws://10.10.10.99:50000"); 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(); } } } }
接下來就是測試階段,首先運行窗體程序。
測試方法1:打開瀏覽器,F12進入調試模式,在Console中輸入測試代碼。(我使用的是谷歌瀏覽器)
ws = new WebSocket("ws://10.10.10.99:50001"); ws.onopen = function() { ws.send('websocekt測試'); }; ws.onmessage = function(e) { alert("收到服務端的消息:" + e.data); };
輸入完畢后按回車執行,這時就可以在命令行中看到傳過來的數據了。
測試方法2:寫html腳本進行通信。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <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://10.10.10.99:50000/'); // 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> <form id="sendForm"> <input id="sendText" placeholder="Text to send" /> </form> <pre id="incomming"></pre> </body> </html>
到這里就結束了,哪里說得不明確希望大家加以補充。
參考:https://www.cnblogs.com/cjm123/p/9674506.html