You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

345 lines
15 KiB

using Container.Common;
using Container.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Windows;
using WebSocket4Net;
namespace Container.Services
{
public class WebSocketManageForLive
{
private WebSocket websocket = null;
App app = ((App)System.Windows.Application.Current);
public delegate void WebSocketReceiveDelegate(string type, string message);
public static event WebSocketReceiveDelegate WebSocketReceiveEvent;
private Class_Log log = new Class_Log();
bool reconnect = false;
#region WebSocketClient
public void OpenWebSocket()
{
try
{
log.WriteLogFile(app.deviceid, "live");
string sendmsg = "ip=" + app.deviceid;
websocket = new WebSocket(ConfigurationManager.AppSettings["websocketForLive"] + "?" + sendmsg);// 地址
log.WriteLogFile(ConfigurationManager.AppSettings["websocketForLive"], "live");
websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error);
websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
websocket.Open();
//websocket.Opened += new EventHandler(websocket_Opened);
websocket.Closed += new EventHandler(websocket_Closed);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
void websocket_Closed(object sender, EventArgs e)
{
if (!reconnect)
{
reconnect = true;
ReConnect();
}
}
public void CloseWebSocket()
{
//if (websocket != null)
// websocket.Close();
}
void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
log.WriteLogFile(e.Message, "WebSocketForLiveLog");
string type = "";
Dictionary<string, Object> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Object>>(e.Message);
if (dic["Content"] != null && dic["SenderID"] != null)
{
Dictionary<string, Object> Commands = JsonConvert.DeserializeObject<Dictionary<string, Object>>(dic["Content"].ToString());
if (!string.IsNullOrEmpty(Commands["Type"].ToString()))
{
type = Commands["Type"].ToString().ToLower();
}
if (type.Trim().Equals("live"))
{
string liveCode = string.Empty;
string mallCode = string.Empty;
//Live live = JsonConvert.DeserializeObject<Live>(Commands["parameter"].ToString());
//app.live.HFilePath = live.HFilePath;
//app.live.Likes = live.Likes;
//app.live.LiveCode = live.LiveCode;
//app.live.liveurl = live.liveurl;
//app.live.MallCode = live.MallCode;
//app.live.SenderID = live.SenderID;
//app.live.VFilePath = live.VFilePath;
//app.live.WatchNum = live.WatchNum;
//app.live = live;
Dictionary<string, Object> liveData = JsonConvert.DeserializeObject<Dictionary<string, Object>>(Commands["Parameter"].ToString());
if (!string.IsNullOrEmpty(liveData["MallCode"].ToString()))
{
mallCode = liveData["MallCode"].ToString();
}
if (!string.IsNullOrEmpty(liveData["LiveCode"].ToString()))
{
liveCode = liveData["LiveCode"].ToString();
}
app.live.LiveCode = liveCode;
app.live.MallCode = mallCode;
app.live.MallName = string.IsNullOrEmpty(liveData["MallName"].ToString()) ? "" : liveData["MallName"].ToString();
app.live.QRCode = string.IsNullOrEmpty(liveData["QrCode"].ToString()) ? "" : liveData["QrCode"].ToString();
app.live.ShopName = string.IsNullOrEmpty(liveData["shopName"].ToString()) ? "" : liveData["shopName"].ToString();
string livePath = string.Empty;
if (!string.IsNullOrEmpty(liveData["liveurl"].ToString()))
{
livePath = liveData["liveurl"].ToString();
}
app.live.LiveUrl = livePath;
app.live.FloorName = string.IsNullOrEmpty(liveData["floorName"].ToString()) ? "" : liveData["floorName"].ToString();
app.live.HouseNum = string.IsNullOrEmpty(liveData["HouseNum"].ToString()) ? "" : liveData["HouseNum"].ToString();
app.live.LogoPath = string.IsNullOrEmpty(liveData["LogoPath"].ToString()) ? "" : liveData["LogoPath"].ToString();
var senderid = dic["SenderID"].ToString();
app.live.SenderID = senderid.LastIndexOf('/') == senderid.Length - 1 ? senderid.Substring(0, senderid.LastIndexOf('/')) : senderid;
app.live.HFilePath = string.IsNullOrEmpty(liveData["HFilePath"].ToString()) ? "" : liveData["HFilePath"].ToString();
app.live.VFilePath = JsonConvert.DeserializeObject<List<string>>(liveData["VFilePath"].ToString());
app.live.CouponInfo = liveData["couponInfo"] ==null?null: JsonConvert.DeserializeObject<CouponInfo>(liveData["couponInfo"].ToString());
log.WriteLogFile("------" + JsonConvert.SerializeObject(app.live.CouponInfo), "222");
}
else if (type.Trim().Equals("shutdownlive"))
{
app.live.LiveUrl = "";
app.live.HFilePath = "";
app.live.VFilePath = new List<string>();
app.live.LiveCode = "";
app.live.MallCode = "";
app.live.OldLiveCode = "";
}
else if (type.Trim().Equals("like") || type.Trim().Equals("watchnum"))
{
Dictionary<string, Object> liveData = JsonConvert.DeserializeObject<Dictionary<string, Object>>(Commands["Parameter"].ToString());
app.live.Likes = Convert.ToInt32(liveData["Likes"].ToString());
app.live.WatchNum = Convert.ToInt32(liveData["WatchNum"].ToString());
}
else if (type.Trim().Equals("livecoupon")||type.Trim().Equals( "getcoupon"))
{
app.live.CouponInfo = JsonConvert.DeserializeObject<CouponInfo>(Commands["Parameter"].ToString());
app.curLive.CouponInfo = app.live.CouponInfo;
}
else if (type.Trim().Equals("shutdowncoupon"))
{
app.live.CouponInfo = null;
app.curLive.CouponInfo = null;
}
else if (type.Trim().Equals("playprog"))
{
Dictionary<string, Object> progData = JsonConvert.DeserializeObject<Dictionary<string, Object>>(Commands["Parameter"].ToString());
if (!string.IsNullOrEmpty(progData["ServerTime"].ToString()))
{
WebSocketManageForLive.SetLocalTimeByStr(progData["ServerTime"].ToString());
string closeTime = Convert.ToDateTime(progData["ServerTime"]).AddHours(1).ToString("yyyy-MM-dd HH" + ":00:00");
app.CloseServerTime = Convert.ToDateTime(closeTime);
}
List<PlayProg> itemList = JsonConvert.DeserializeObject<List<PlayProg>>(progData["Orders"].ToString());
if (app.ScreenWidth > app.ScreenHeight)
{
itemList = itemList.FindAll(i => i.OrderType == 1);
}
else
{
itemList = itemList.FindAll(i => i.OrderType == 2);
}
foreach (var item in itemList)
{
HttpClient httpClient = new HttpClient();
string fileName = "";
if (httpClient.DownLoadImage(item.FilePath, "BrandImageFile", ref fileName))
{
item.FilePath = fileName;
}
else
{
log.WriteLogFile("商户发布广告图下载失败");
}
}
app.playProgList = itemList;
}
else if (type.Trim().Equals("shutdownprog"))
{
Dictionary<string, Object> progData = JsonConvert.DeserializeObject<Dictionary<string, Object>>(Commands["Parameter"].ToString());
if (!string.IsNullOrEmpty(progData["ServerTime"].ToString()))
{
WebSocketManageForLive.SetLocalTimeByStr(progData["ServerTime"].ToString());
string closeTime = Convert.ToDateTime(progData["ServerTime"]).AddHours(1).ToString("yyyy-MM-dd HH" + ":00:00");
app.CloseServerTime = Convert.ToDateTime(closeTime);
}
List<ShutDownProg> itemList = JsonConvert.DeserializeObject<List<ShutDownProg>>(progData["Orders"].ToString());
app.shutDownProgList = itemList;
//List<PlayProg> deepCopyList = Clone<PlayProg>(app.playProgList);
//foreach (var item in app.playProgList)
//{
// if (itemList.FindAll(i => i.Code == item.Code).Count > 0)
// {
// deepCopyList.Remove(item);
// }
//}
//app.playProgList = deepCopyList;
}
}
if (WebSocketReceiveEvent != null)
{
WebSocketReceiveEvent(type, "");
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "WebSocketLogLive");
}
}
/// <summary>
/// Clones the specified list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="List">The list.</param>
/// <returns>List{``0}.</returns>
public List<T> Clone<T>(object List)
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, List);
objectStream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(objectStream) as List<T>;
}
}
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime sysTime);
[StructLayout(LayoutKind.Sequential)]
public struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
public short wYear;
[MarshalAs(UnmanagedType.U2)]
public short wMonth;
[MarshalAs(UnmanagedType.U2)]
public short wDayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short wDay;
[MarshalAs(UnmanagedType.U2)]
public short wHour;
[MarshalAs(UnmanagedType.U2)]
public short wMinute;
[MarshalAs(UnmanagedType.U2)]
public short wSecond;
[MarshalAs(UnmanagedType.U2)]
public short wMilliseconds;
}
public static bool SetLocalTimeByStr(string timestr)
{
bool flag = false;
SystemTime sysTime = new SystemTime();
DateTime dt = Convert.ToDateTime(timestr);
sysTime.wYear = Convert.ToInt16(dt.Year);
sysTime.wMonth = Convert.ToInt16(dt.Month);
sysTime.wDay = Convert.ToInt16(dt.Day);
sysTime.wHour = Convert.ToInt16(dt.Hour);
sysTime.wMinute = Convert.ToInt16(dt.Minute);
sysTime.wSecond = Convert.ToInt16(dt.Second);
try
{
flag = WebSocketManageForLive.SetLocalTime(ref sysTime);
}
catch (Exception e)
{
Console.WriteLine("SetSystemDateTime函数执行异常" + e.Message);
}
return flag;
}
void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
{
log.WriteLogFile(e.Exception.Message + e.Exception.StackTrace, "WebSocketErrorLog");
//try
//{
// if (websocket != null)
// websocket.Close();
//}
//catch
//{
//}
//ReConnect();
}
/// <summary>
/// websocket重连
/// </summary>
private void ReConnect()
{
try
{
Action ac = new Action(() =>
{
while (true)
{
try
{
if (websocket.State == WebSocketState.Closed)
{
Thread.Sleep(30000);
if (websocket.State == WebSocketState.Closed)
websocket.Open();
}
if (websocket.State == WebSocketState.Open)
{
//reconnect = false;
break;
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "WebSocketErrorLog");
}
finally
{
Thread.Sleep(3000);
}
}
});
ac.BeginInvoke((o) =>
{
reconnect = false;
}, null);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "WebSocketErrorLog");
}
}
#endregion
}
}