1、VS2017创建winform项目
2、Nuget中搜索安装 SuperWebSocketNETServer
二、WebSocket服务端功能实现1、由于有使用到log4net,在开始实现功能前,需要对log4net进行相关设置,设置参考https://blog.csdn.net/liwan09/article/details/106266346
2、界面设置
3、实现功能代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using SuperWebSocket;
using log4net;
using Bosch.Rtns.Sockect.Model;
using Bosch.Rtns.Sockect.CommonUtils;
namespace Bosch.Rtns.Sockect
{
public partial class frmMain : Form
{
private WebSocketServer webSocketServer;
ILog loggerManager;
Dictionary socketSessionList = new Dictionary();//记录链接的客户端数据
public frmMain()
{
InitializeComponent();
}
///
/// load
///
///
///
private void frmMain_Load(object sender, EventArgs e)
{
loggerManager=LogManager.GetLogger("Logger");
txtIPAddress.Text = "127.0.0.1";
txtPort.Text = "1414";
btnEnd.Enabled = false;
}
///
///开启服务
///
///
///
private void btnStart_Click(object sender, EventArgs e)
{
string ipAddress = txtIPAddress.Text.Trim();
string port = txtPort.Text.Trim();
if (string.IsNullOrEmpty(ipAddress))
{
txtIPAddress.Focus();
MessageBox.Show("请输入IP地址!");
return;
}
if (string.IsNullOrEmpty(port))
{
txtPort.Focus();
MessageBox.Show("请输入端口号!");
return;
}
webSocketServer = new WebSocketServer();
webSocketServer.NewSessionConnected += Sockect_NewSessionConnected;
webSocketServer.NewMessageReceived += Sockect_NewMessageReceived;
webSocketServer.SessionClosed += Sockect_SessionClosed;
if (!webSocketServer.Setup(ipAddress,Convert.ToInt32(port)))
{
txtLogInfo.Text += "设置Socket服务侦听地址失败!rn";
loggerManager.Error("设置Socket服务侦听地址失败!rn");
return;
}
if (!webSocketServer.Start())
{
txtLogInfo.Text += "启动WebSocket服务侦听失败!rn";
loggerManager.Error("启动WebSocket服务侦听失败!rn");
return;
}
txtLogInfo.Text += "Socket启动服务成功!rn";
loggerManager.Info("Socket启动服务成功!rn");
txtIPAddress.Enabled = false;
txtPort.Enabled = false;
btnStart.Enabled = false;
btnEnd.Enabled = true;
}
///
/// 关闭服务
///
///
///
private void btnEnd_Click(object sender, EventArgs e)
{
if (webSocketServer != null)
{
webSocketServer.Stop();
webSocketServer = null;
}
txtIPAddress.Enabled = true;
txtPort.Enabled = true;
btnStart.Enabled = true;
btnEnd.Enabled = false;
}
///
/// 新的Socket连接事件
///
///
private void Sockect_NewSessionConnected(WebSocketSession session)
{
string logMsg = string.Format("{0} 与客户端{1}创建新会话", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), GetwebSocketSessionName(session))+"rn";
this.Invoke(new Action(() =>
{
txtLogInfo.Text += logMsg;
}));
loggerManager.Info(logMsg);
socketSessionList.Add(session, "");
}
///
/// 消息接收事件
///
///
/// 接收的消息
private void Sockect_NewMessageReceived(WebSocketSession session, string value)
{
string logMsg = string.Format("{0} 从客户端{1}接收新的消息:rn{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), GetwebSocketSessionName(session),value) + "rn";
this.Invoke(new Action(() =>
{
txtLogInfo.Text += logMsg;
}));
loggerManager.Info(logMsg);
ReceiveData receiveData = JsonHelper.ConvertToEntity(value);
//退出登录
if (receiveData.MessageType == "3")
{
//调用weiapi接口,更新在线用户的在线状态
socketSessionList.Remove(session);
session.Close(SuperSocket.SocketBase.CloseReason.ClientClosing);//断开连接
}
else
{
if(receiveData.MessageType == "4")//设备故障推送
{
EquipmentFault equipmentFault = JsonHelper.ConvertToEntity(receiveData.MessageContent);
}
else
{
socketSessionList[session] = receiveData.MessageContent;//记录app端的设备id
}
}
}
///
/// sockect客户端断开连接事件
///
///
///
private void Sockect_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
string logMsg = string.Format("{0} 与客户端{1}的会话被关闭 原因:{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), GetwebSocketSessionName(session), value) + "rn";
this.Invoke(new Action(() =>
{
txtLogInfo.Text += logMsg;
}));
loggerManager.Info(logMsg);
socketSessionList.Remove(session);
}
///
/// 获取连接的客户端的ip地址
///
///
private static string GetwebSocketSessionName(WebSocketSession webSocketSession)
{
string id= HttpUtility.UrlDecode(webSocketSession.SessionID);//获取sessionid
var remoteClient = webSocketSession.RemoteEndPoint;
return remoteClient.Address + ":" + remoteClient.Port.ToString();
}
///
/// 发送消息
///
///
///
private void SendMessage(WebSocketSession session, string msg)
{
//向所有客户端发送消息
//foreach (var sendSession in session.AppServer.GetAllSessions())
//{
// sendSession.Send(msg);
//}
session.Send(msg);//向指定的客户端发送消息
}
}
}
相关实体类代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bosch.Rtns.Sockect.Model
{
///
/// 设备故障信息
///
public class EquipmentFault
{
///
/// 目标手机设备ID
///
public string TargetPhoneID { get; set; }
///
/// 故障发生时间
///
public DateTime FaultTime { get; set; }
///
/// 消息id
///
public string MessageUID { get; set; }
///
/// 消息标题
///
public string MessageTitle { get; set; }
///
/// 发送给App(消息类型)
///
public string SubAPPname { get; set; }
///
/// 故障等级 Low,Default,High,Emergent
///
public string EmergenceLevel { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bosch.Rtns.Sockect.Model
{
///
/// 接收的消息
///
public class ReceiveData
{
///
/// 接收的消息类型 1:App端登录 2:设备故障信息推送
///
public string MessageType { get; set; }
///
/// 消息内容
///
public string MessageContent { get; set; }
}
}
Json帮助类代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Bosch.Rtns.Sockect.CommonUtils
{
///
/// Json帮助类
///
public class JsonHelper
{
///
/// object转json
///
///
///
public static string ConvertObjToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
///
/// Json字符串转实体类数据
///
///
///
///
public static T ConvertToEntity(string jsonValue)
{
return JsonConvert.DeserializeObject(jsonValue);
}
///
/// Json字符串转List
///
///
///
///
public static List ConvertToList(string jsonValue)
{
return JsonConvert.DeserializeObject>(jsonValue);
}
}
}
4、客户端代码(html)
Web sockets test
服务器地址:



