using Fleck;
using Mono.Web;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace demoforQQ.WebSocket
{
public partial class WebSocketForm : Form
{
public WebSocketForm()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void WebSocketForm_Load(object sender, EventArgs e)
{
runSocket();
}
static void runSocket()
{
//FleckLog.Level = LogLevel.Debug;
//var allSockets = new List<IWebSocketConnection>();
Dictionary<string, dynamic> dicSocketServer = new Dictionary<string, dynamic>();
Dictionary<string, dynamic> dicSocketCustomer = new Dictionary<string, dynamic>();
string userIp = "";
var server = new WebSocketServer("ws://0.0.0.0:1818");
server.Start(socket =>
{
userIp = socket.ConnectionInfo.ClientIpAddress.ToString();
var ClientIp = socket.ConnectionInfo.ClientIpAddress;
var Path = socket.ConnectionInfo.Path;
var url = "http://" + ClientIp + Path;
Uri myUri = new Uri(url);
string role = HttpUtility.ParseQueryString(myUri.Query).Get("role");
var ClientPort = socket.ConnectionInfo.ClientPort;
var key = role + ClientPort;
socket.OnOpen = () =>
{
Console.WriteLine(key + "已上线!");
//allSockets.Add(socket);
if (role == "customer")
{
if (!dicSocketCustomer.ContainsKey(key))
{
dicSocketCustomer.Add(key, socket);
}
}
if (role == "server")
{
if (!dicSocketServer.ContainsKey(key))
{
dicSocketServer.Add(key, socket);
}
}
};
socket.OnClose = () =>
{
Console.WriteLine(key + "下线了!");
//allSockets.Remove(socket);
if (role == "customer")
{
dicSocketCustomer.Remove(key);
}
if (role == "server")
{
dicSocketServer.Remove(key);
}
};
socket.OnMessage = message =>
{
//Console.WriteLine("消息发送者:" + key);
//Console.WriteLine("消息:" + message);
/*Console.WriteLine("role:" + role);*/
if (role == "server")
{
//广播给 customer
foreach (var perCustomer in dicSocketCustomer)
{
var sc = perCustomer.Value;
sc.Send(message);
}
}
if (role == "customer")
{
//Console.WriteLine(dicSocketCustomer.Count);
//广播给 customer ,server收不到信息
foreach (var perCustomer in dicSocketCustomer)
{
var sc = perCustomer.Value;
sc.Send(message);
}
}
};
});
}
}
}
此项目是做收银端和客显端显示,有customer和server身份区分,对应https://blog.csdn.net/weixin_42674576/article/details/121703047?spm=1001.2014.3001.5501,可根据自己需求做调整
|