using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using System.Threading;
using Hangjing.SQLServerDAL.serverinterface;
namespace SuperSocket.SocketService
{
public class MESSAGETYPE
{
/// <summary>
/// 1表示消息
/// </summary>
public const uint MSG = 1;
/// <summary>
/// 0表示订单
/// </summary>
public const uint ORDER = 0;
}
/// <summary>
/// 自定义连接类MySession,继承AppSession,并传入到AppSession
/// </summary>
public class NoticeSession : AppSession<NoticeSession>
{
bool isSendMessage = false;
public StringDictionary Cookies { get; private set; }
/// <summary>
/// 数据编号,配送员,或者商家编号等
/// </summary>
public int DataID
{
get;
set;
}
/// <summary>
/// 类型:1表示骑士,2表示商家
/// </summary>
public int Type
{
set;
get;
}
/// <summary>
/// 用户名;
/// </summary>
public String UserName
{
get;
set;
}
/// <summary>
/// 密码
/// </summary>
public String Password
{
get;
set;
}
protected override void OnSessionStarted()
{
}
protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
{
//Logger.Debug("NoticeSession.OnSessionStarted:Unknow request");
}
protected override void HandleException(Exception e)
{
//Logger.Debug("NoticeSession.OnSessionStarted:Unknow request");
}
protected override void OnSessionClosed(CloseReason reason)
{
Logout();
base.OnSessionClosed(reason);
}
/// <summary>
/// 根据登录的参数,保存cookie ,并设置属性
/// </summary>
public void SetCookie(string cookieValue)
{
var cookies = new StringDictionary();
if (!string.IsNullOrEmpty(cookieValue))
{
string[] pairs = cookieValue.Split(';');
int pos;
string key, value;
foreach (var p in pairs)
{
pos = p.IndexOf('=');
if (pos > 0)
{
key = p.Substring(0, pos).Trim();
pos += 1;
if (pos < p.Length)
value = p.Substring(pos).Trim();
else
value = string.Empty;
cookies[key] = Uri.UnescapeDataString(value);
}
}
}
this.Cookies = cookies;
this.UserName = Cookies["name"];
this.Password = Cookies["password"];
this.Type = Convert.ToInt32(Cookies["type"]);
}
/// <summary>
/// 向客户端发送消息(0 表示订单 ,1表示消息)
/// </summary>
/// <param name="type">(0 表示订单 ,1表示消息)</param>
/// <param name="message">消息内容(json)</param>
public void SendMessage(uint type, String message)
{
while (isSendMessage)
{
Thread.Sleep(1);
}
isSendMessage = true;
String value = "";
switch (type)
{
case MESSAGETYPE.ORDER:
value = "ORDER::" + message;
break;
case MESSAGETYPE.MSG:
value = "MSG::" + message;
break;
}
this.Send(value);
isSendMessage = false;
}
/// <summary>
/// session退出,对应骑士下线
/// </summary>
public void Logout()
{
if (DataID != 0 && Type == 1)
{
APPUser user = new APPUser(this.UserName, this.Password, this.SessionID, this.Type);
if (user.app != null)
{
user.app.UpdateLoginState(this.SessionID, 0);
}
}
}
/// <summary>
/// 根据编号为类型获取session
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public NoticeSession GetSession(int id, int type)
{
NoticeSession session = this.AppServer.GetAllSessions().Where(a => a.DataID == id && a.Type == type).FirstOrDefault();
if (session != null)
{
return session;
}
else
{
return null;
}
}
}
}
View Code
NoticeServer代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace Hangjing.WCFService
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class UserNoticeService : IUserNoticeService
{
/// <summary>
/// 添加消息
/// </summary>
/// <param name="userid">用户编号</param>
/// <param name="usertype">用户类型 1表示骑士,2表示商家</param>
/// <param name="messagetype">消息类型 消息类型:0表示订单,1表示纯消息。</param>
/// <param name="message">消息json</param>
public void AddMessage(int userid, int usertype, int messagetype, string message)
{
NoticeInfo model = new NoticeInfo();
model.UserId = userid;
model.UserType = usertype;
model.MessageType = messagetype;
model.Message = message;
NoticeManager nm = NoticeManager.GetInstance();
nm.Add(model);
}
}
}
View Code
使用委托及时传递消息
当UserNoticeService.AddMessage 接收到消息后,如何传递给 Windows Service时,也纠结了好久,直到就快放弃思考,准备用消息队列来实现时,才想到委托。这个东西吧,一直觉得很多神奇,之前也花了很多时间去理解,一直觉得似懂非懂的感觉,原来是没有真正的应用。代码部分就比较简单了,以下是NoticeManager.cs相关代码,在UserNoticeService.AddMessage中执行添加的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Hangjing.WCFService
{
/// <summary>
/// 对消息的管理
/// </summary>
public class NoticeManager
{
public static List<NoticeInfo> NoticeList = new List<NoticeInfo>();
public static object m_SessionSyncRoot = new object();
public event AddHandler AddEvent = null;
private static NoticeManager instance;
static NoticeManager() //类型构造器,确保线程安全
{
instance = new NoticeManager();
}
private NoticeManager() //构造方法为private,这就堵死了外界利用new创建此类型实例的可能
{
Thread.Sleep(50);//此处模拟创建对象耗时
}
public static NoticeManager GetInstance() //次方法是获得本类实例的唯一全局访问点
{
return instance;
}
/// <summary>
/// 添加方法
/// </summary>
/// <param name="notice"></param>
public void Add(NoticeInfo model)
{
//后期再考虑消息的存储
//foreach (var item in NoticeManager.NoticeList)
//{
// if (item.UserId == model.UserId && item.UserType == model.UserType)
// {
// lock (NoticeManager.m_SessionSyncRoot)
// {
// NoticeManager.NoticeList.Remove(item);
// }
// }
//}
//lock (NoticeManager.m_SessionSyncRoot)
//{
// NoticeManager.NoticeList.Add(model);
//}
if (this.AddEvent != null)
{
this.AddEvent(model);
}
}
}
public delegate void AddHandler(NoticeInfo notice);