Chatlog.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * 由SharpDevelop创建。
  3. * 用户: 王刚
  4. * 日期: 2017/3/17
  5. * 时间: 9:23
  6. *
  7. * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
  8. */
  9. using System;
  10. using System.IO;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using Newtonsoft.Json.Linq;
  14. using System.Runtime.Serialization;
  15. using System.Runtime.Serialization.Formatters.Binary;
  16. /// <summary>
  17. /// 聊天记录类,将记录保存在本地.
  18. /// </summary>
  19. [Serializable]
  20. public class Chatlog
  21. {
  22. const int MAX_MSG_COUNT = 500;
  23. string _uid = "", _friendid = "";
  24. public Dictionary<int, string> friendschat = new Dictionary<int, string>();
  25. public Dictionary<int, string> mywords = new Dictionary<int, string>();
  26. public void FriendSays(int ts, string talk)
  27. {
  28. addTalk(friendschat, ts, talk);
  29. }
  30. public void MeSay(string talk)
  31. {
  32. addTalk(mywords, (int)DateTime.Now.ToUnixTimeStamp(), talk);
  33. }
  34. public Chatlog(string uid, string friendid)
  35. {
  36. this._uid = uid;
  37. this._friendid = friendid;
  38. if (File.Exists(GetFileName()))
  39. {
  40. using(var sr=new FileStream(GetFileName(), FileMode.Open)) {
  41. var bf = new BinaryFormatter();
  42. var clog = (Chatlog)bf.Deserialize(sr);
  43. this.friendschat = clog.friendschat;
  44. this.mywords = clog.mywords;
  45. }
  46. }
  47. }
  48. /// <summary>
  49. /// 析构的时候自动保存
  50. /// </summary>
  51. ~Chatlog()
  52. {
  53. Save();
  54. }
  55. public void Save()
  56. {
  57. using (var sw = new FileStream(GetFileName(), FileMode.Create))
  58. {
  59. new BinaryFormatter().Serialize(sw, this);
  60. }
  61. }
  62. void addTalk(Dictionary<int, string> log, int ts, string talk)
  63. {
  64. if (!log.ContainsKey(ts))
  65. {
  66. log.Add(ts, talk);
  67. if (log.Count > MAX_MSG_COUNT)
  68. {
  69. log.Remove(log.Keys.First());
  70. }
  71. }
  72. }
  73. string GetFileName()
  74. {
  75. if (!Directory.Exists(UnityHelper.GetUserDataPath() + "/chatlog/"))
  76. { // 防御
  77. Directory.CreateDirectory(UnityHelper.GetUserDataPath() + "/chatlog/");
  78. }
  79. return UnityHelper.GetUserDataPath() + "/chatlog/" + _uid + "_" + _friendid; // 无后缀名
  80. }
  81. }