話不多說,先上圖


背景:
微信聊天,經常會遇見視頻發不了,嗯,還有聊天不方便的問題,于是我就自己買了服務器,部署了一套可以直接在微信打開的網頁進行聊天,這樣只需要發送個url給朋友,就能聊天了!
由于自己無聊弄著玩的,代碼比較粗糙,各位多指正!
1、首先安裝SignalR,這步我就不做過多說明了
安裝好以后在根目錄新建一個Hubs檔案夾,做用戶的注冊和通知
MessageHub.cs 檔案
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace SignalR.Hubs
{
[HubName("MessageHub")]
public class MessageHub : Hub
{
private readonly ChatTicker ticker;
public MessageHub()
{
ticker = ChatTicker.Instance;
}
public void register(string username, string group = "default")
{
var list = (List<SiginalRModel>)HttpRuntime.Cache.Get("msg_hs");
if (list == null)
{
list = new List<SiginalRModel>();
}
if (list.Any(x => x.connectionId == Context.ConnectionId))
{
Clients.Client(Context.ConnectionId).broadcastMessage("已經注冊,無需再次注冊");
}
else if (list.Any(x => x.name == username))
{
var model = list.Where(x => x.name == username && x.group == group).FirstOrDefault();
if (model != null)
{
//注冊到全域
ticker.GlobalContext.Groups.Add(Context.ConnectionId, group);
Clients.Client(model.connectionId).exit();
ticker.GlobalContext.Groups.Remove(model.connectionId, group);
list.Remove(model);
model.connectionId = Context.ConnectionId;
list.Add(model);
Clients.Group(group).removeUserList(model.connectionId);
Thread.Sleep(200);
var gourpList = list.Where(x => x.group == group).ToList();
Clients.Group(group).appendUserList(Context.ConnectionId, gourpList);
HttpRuntime.Cache.Insert("msg_hs", list);
// Clients.Client(model.connectionId).broadcastMessage("名稱重復,只能注冊一個");
}
//Clients.Client(Context.ConnectionId).broadcastMessage("名稱重復,只能注冊一個");
}
else
{
list.Add(new SiginalRModel() { name = username, group = group, connectionId = Context.ConnectionId });
//注冊到全域
ticker.GlobalContext.Groups.Add(Context.ConnectionId, group);
Thread.Sleep(200);
var gourpList = list.Where(x => x.group == group).ToList();
Clients.Group(group).appendUserList(Context.ConnectionId, gourpList);
HttpRuntime.Cache.Insert("msg_hs", list);
}
}
public void Say(string msg)
{
var list = (List<SiginalRModel>)HttpRuntime.Cache.Get("msg_hs");
if (list == null)
{
list = new List<SiginalRModel>();
}
var userModel = list.Where(x => x.connectionId == Context.ConnectionId).FirstOrDefault();
if (userModel != null )
{
Clients.Group(userModel.group).Say(userModel.name, msg);
}
}
public void Exit()
{
OnDisconnected(true);
}
public override Task OnDisconnected(bool s)
{
var list = (List<SiginalRModel>)HttpRuntime.Cache.Get("msg_hs");
if (list == null)
{
list = new List<SiginalRModel>();
}
var closeModel = list.Where(x => x.connectionId == Context.ConnectionId).FirstOrDefault();
if (closeModel != null)
{
list.Remove(closeModel);
Clients.Group(closeModel.group).removeUserList(Context.ConnectionId);
}
HttpRuntime.Cache.Insert("msg_hs", list);
return base.OnDisconnected(s);
}
}
public class ChatTicker
{
#region 實作一個單例
private static readonly ChatTicker _instance =
new ChatTicker(GlobalHost.ConnectionManager.GetHubContext<MessageHub>());
private readonly IHubContext m_context;
private ChatTicker(IHubContext context)
{
m_context = context;
//這里不能直接呼叫Sender,因為Sender是一個不退出的“死回圈”,否則這個建構式將不會退出,
//其他的流程也將不會再執行下去了,所以要采用異步的方式,
//Task.Run(() => Sender());
}
public IHubContext GlobalContext
{
get { return m_context; }
}
public static ChatTicker Instance
{
get { return _instance; }
}
#endregion
}
public class SiginalRModel {
public string connectionId { get; set; }
public string group { get; set; }
public string name { get; set; }
}
}
我把類和方法都寫到一塊了,大家最好是分開!
接下來是控制器
HomeController.cs
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Client;
using SignalR.Hubs;
using SignalR.ViewModels;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace SignalR.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetV(string v)
{
if (!string.IsNullOrEmpty(v))
{
string url = RedisHelper.Get(v)?.ToString();
if (!string.IsNullOrEmpty(url))
{
return Json(new { isOk = true, m = url }, JsonRequestBehavior.AllowGet);
}
return Json(new { isOk = false}, JsonRequestBehavior.AllowGet);
}
return Json(new { isOk = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult getkey(string url)
{
if (!string.IsNullOrEmpty(url))
{
var s = "v" + Util.GetRandomLetterAndNumberString(new Random(), 5).ToLower();
var dt = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 04:00:00"));
int min = Convert.ToInt16((dt - DateTime.Now).TotalMinutes);
RedisHelper.Set(s, url, min);
return Json(new { isOk = true, m = s }, JsonRequestBehavior.AllowGet);
}
return Json(new { isOk = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult upfile()
{
try
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null)
{
var imgList = new List<string>() { ".gif", ".jpg", ".bmp", ".png" };
var videoList = new List<string>() { ".mp4" };
FileModel fmodel = new FileModel();
string name = Guid.NewGuid().ToString();
string fileExt = Path.GetExtension(file.FileName).ToLower();//上傳檔案擴展名
string path = Server.MapPath("~/files/") + name + fileExt;
file.SaveAs(path);
string extension = new FileInfo(path).Extension;
if (extension == ".mp4")
{
fmodel.t = 2;
}
else if (imgList.Contains(extension))
{
fmodel.t = 1;
}
else
{
fmodel.t = 0;
}
string url = Guid.NewGuid().ToString();
fmodel.url = "http://" + Request.Url.Host;
if (Request.Url.Port != 80)
{
fmodel.url += ":" + Request.Url.Port;
}
fmodel.url += "/files/" + name + fileExt;
GetImageThumb(Server.MapPath("~") + "files\\" + name + fileExt, name);
return Json(new { isOk = true, m = "file:" + JsonConvert.SerializeObject(fmodel) }, JsonRequestBehavior.AllowGet);
}
}
}
catch(Exception ex)
{
Log.Info(ex);
}
return Content("");
}
public string GetImageThumb(string localVideo,string name)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string ffmpegPath = path + "/ffmpeg.exe";
string oriVideoPath = localVideo;
int frameIndex = 5;
int _thubWidth;
int _thubHeight;
GetMovWidthAndHeight(localVideo, out _thubWidth, out _thubHeight);
int thubWidth = 200;
int thubHeight = _thubWidth == 0 ? 200 : (thubWidth * _thubHeight / _thubWidth );
string thubImagePath = path + "files\\" + name + ".jpg";
string command = string.Format("\"{0}\" -i \"{1}\" -ss {2} -vframes 1 -r 1 -ac 1 -ab 2 -s {3}*{4} -f image2 \"{5}\"", ffmpegPath, oriVideoPath, frameIndex, thubWidth, thubHeight, thubImagePath);
Cmd.RunCmd(command);
return name;
}
/// <summary>
/// 獲取視頻的幀寬度和幀高度
/// </summary>
/// <param name="videoFilePath">mov檔案的路徑</param>
/// <returns>null表示獲取寬度或高度失敗</returns>
public static void GetMovWidthAndHeight(string videoFilePath, out int width, out int height)
{
try
{
//執行命令獲取該檔案的一些資訊
string ffmpegPath = AppDomain.CurrentDomain.BaseDirectory + "/ffmpeg.exe";
string output;
string error;
ExecuteCommand("\"" + ffmpegPath + "\"" + " -i " + "\"" + videoFilePath + "\"", out output, out error);
if (string.IsNullOrEmpty(error))
{
width = 0;
height = 0;
}
//通過正則運算式獲取資訊里面的寬度資訊
Regex regex = new Regex("(\\d{2,4})x(\\d{2,4})", RegexOptions.Compiled);
Match m = regex.Match(error);
if (m.Success)
{
width = int.Parse(m.Groups[1].Value);
height = int.Parse(m.Groups[2].Value);
}
else
{
width = 0;
height = 0;
}
}
catch (Exception)
{
width = 0;
height = 0;
}
}
public static void ExecuteCommand(string command, out string output, out string error)
{
try
{
//創建一個行程
Process pc = new Process();
pc.StartInfo.FileName = command;
pc.StartInfo.UseShellExecute = false;
pc.StartInfo.RedirectStandardOutput = true;
pc.StartInfo.RedirectStandardError = true;
pc.StartInfo.CreateNoWindow = true;
//啟動行程
pc.Start();
//準備讀出輸出流和錯誤流
string outputData = https://www.cnblogs.com/colyn/p/string.Empty;
string errorData = string.Empty;
pc.BeginOutputReadLine();
pc.BeginErrorReadLine();
pc.OutputDataReceived += (ss, ee) =>
{
outputData += ee.Data;
};
pc.ErrorDataReceived += (ss, ee) =>
{
errorData += ee.Data;
};
//等待退出
pc.WaitForExit();
//關閉行程
pc.Close();
//回傳流結果
output = outputData;
error = errorData;
}
catch (Exception)
{
output = null;
error = null;
}
}
}
public class Util
{
public static string GetRandomLetterAndNumberString(Random random, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("length");
}
char[] pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
string result = "";
int n = pattern.Length;
for (int i = 0; i < length; i++)
{
int rnd = random.Next(0, n);
result += pattern[rnd];
}
return result;
}
}
class Cmd
{
private static string CmdPath = @"C:\Windows\System32\cmd.exe";
/// <summary>
/// 執行cmd命令 回傳cmd視窗顯示的資訊
/// 多命令請使用批處理命令連接符:
/// <![CDATA[
/// &:同時執行兩個命令
/// |:將上一個命令的輸出,作為下一個命令的輸入
/// &&:當&&前的命令成功時,才執行&&后的命令
/// ||:當||前的命令失敗時,才執行||后的命令]]>
/// </summary>
/// <param name="cmd">執行的命令</param>
public static string RunCmd(string cmd)
{
cmd = cmd.Trim().TrimEnd('&') + "&exit";//說明:不管命令是否成功均執行exit命令,否則當呼叫ReadToEnd()方法時,會處于假死狀態
using (Process p = new Process())
{
p.StartInfo.FileName = CmdPath;
p.StartInfo.UseShellExecute = false; //是否使用作業系統shell啟動
p.StartInfo.RedirectStandardInput = true; //接受來自呼叫程式的輸入資訊
p.StartInfo.RedirectStandardOutput = true; //由呼叫程式獲取輸出資訊
p.StartInfo.RedirectStandardError = true; //重定向標準錯誤輸出
p.StartInfo.CreateNoWindow = true; //不顯示程式視窗
p.Start();//啟動程式
//向cmd視窗寫入命令
p.StandardInput.WriteLine(cmd);
p.StandardInput.AutoFlush = true;
//獲取cmd視窗的輸出資訊
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();//等待程式執行完退出行程
p.Close();
return output;
}
}
}
}
我還是都寫到一塊了,大家記得分開!
SController.cs 這個是針對手機端單獨拎出來的,里面不需要什么內容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SignalR.Controllers
{
public class SController : Controller
{
// GET: S
public ActionResult Index()
{
return View();
}
}
}
根目錄新建一個ViewModels檔案夾,里面新建FileModel.cs檔案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SignalR.ViewModels
{
public class FileModel
{
/// <summary>
/// 1 : 圖片 2:視頻
/// </summary>
public int t { get; set; }
public string url { get; set; }
}
}
RedisHelper.cs
using Microsoft.AspNet.SignalR.Messaging;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using System.Web;
namespace SignalR
{
public class RedisHelper
{
private static string Constr = "xxxx.cn:6379";
private static object _locker = new Object();
private static ConnectionMultiplexer _instance = null;
/// <summary>
/// 使用一個靜態屬性來回傳已連接的實體,如下列中所示,這樣,一旦 ConnectionMultiplexer 斷開連接,便可以初始化新的連接實體,
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
if (Constr.Length == 0)
{
throw new Exception("連接字串未設定!");
}
if (_instance == null)
{
lock (_locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = ConnectionMultiplexer.Connect(Constr);
}
}
}
//注冊如下事件
_instance.ConnectionFailed += MuxerConnectionFailed;
_instance.ConnectionRestored += MuxerConnectionRestored;
_instance.ErrorMessage += MuxerErrorMessage;
_instance.ConfigurationChanged += MuxerConfigurationChanged;
_instance.HashSlotMoved += MuxerHashSlotMoved;
_instance.InternalError += MuxerInternalError;
return _instance;
}
}
static RedisHelper()
{
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IDatabase GetDatabase()
{
return Instance.GetDatabase();
}
/// <summary>
/// 這里的 MergeKey 用來拼接 Key 的前綴,具體不同的業務模塊使用不同的前綴,
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private static string MergeKey(string key)
{
return "SignalR:"+ key;
//return BaseSystemInfo.SystemCode + key;
}
/// <summary>
/// 根據key獲取快取物件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T Get<T>(string key)
{
key = MergeKey(key);
return Deserialize<T>(GetDatabase().StringGet(key));
}
/// <summary>
/// 根據key獲取快取物件
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static object Get(string key)
{
key = MergeKey(key);
return Deserialize<object>(GetDatabase().StringGet(key));
}
/// <summary>
/// 設定快取
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expireMinutes"></param>
public static void Set(string key, object value, int expireMinutes = 0)
{
key = MergeKey(key);
if (expireMinutes > 0)
{
GetDatabase().StringSet(key, Serialize(value), TimeSpan.FromMinutes(expireMinutes));
}
else
{
GetDatabase().StringSet(key, Serialize(value));
}
}
/// <summary>
/// 判斷在快取中是否存在該key的快取資料
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exists(string key)
{
key = MergeKey(key);
return GetDatabase().KeyExists(key); //可直接呼叫
}
/// <summary>
/// 移除指定key的快取
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Remove(string key)
{
key = MergeKey(key);
return GetDatabase().KeyDelete(key);
}
/// <summary>
/// 異步設定
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static async Task SetAsync(string key, object value)
{
key = MergeKey(key);
await GetDatabase().StringSetAsync(key, Serialize(value));
}
/// <summary>
/// 根據key獲取快取物件
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static async Task<object> GetAsync(string key)
{
key = MergeKey(key);
object value = https://www.cnblogs.com/colyn/p/await GetDatabase().StringGetAsync(key);
return value;
}
///
/// 實作遞增
///
///
總體專案結構是這樣的

下期我將把前端代碼列出來,這個我只是為了實作功能,大神勿噴
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/166513.html
標籤:JavaScript
