PageLinkIoi.xaml.vb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. Imports System.Net.Sockets
  2. Public Class PageLinkIoi
  3. Public Const RequestVersion As Integer = 4
  4. Public Const IoiVersion As Integer = 10 '由于已关闭更新渠道,在提升 IoiVersion 时必须提升 RequestVersion
  5. Public Shared PathIoi As String = PathAppdata & "联机模块\IOI 联机模块.exe"
  6. #Region "进程管理"
  7. Private Shared IoiId As String, IoiPassword As String
  8. Private Shared IoiProcess As Process = Nothing
  9. Private Shared IoiState As LoadState = LoadState.Waiting
  10. ''' <summary>
  11. ''' 若 Ioi 正在运行,则结束 Ioi 进程,同时初始化状态数据。返回是否关闭了对应进程。
  12. ''' </summary>
  13. Public Shared Function IoiStop(SleepWhenKilled As Boolean) As Boolean
  14. Return False
  15. End Function
  16. ''' <summary>
  17. ''' 启动 Ioi,并等待初始化完成后退出运行,同时更新 IoiId 与 IoiPassword。
  18. ''' 正常初始化返回 True,需要更新返回 False,其余情况抛出异常。
  19. ''' 若 Ioi 正在运行,则会先停止其运行。
  20. ''' </summary>
  21. Public Shared Function IoiStart() As Boolean
  22. Return False
  23. End Function
  24. 'Ioi 日志
  25. Private Shared Sub IoiLogLine(Content As String)
  26. End Sub
  27. Private Shared LogLinesCount As Integer = 0
  28. Private Shared LastPortsId As String = "" '上一个收到 portssub 的 ID,用于记录端口
  29. #End Region
  30. #Region "时钟"
  31. 'UI 线程刷新
  32. Private Shared UserListIdentifyCache As String = ""
  33. Private Shared RoomListIdentifyCache As String = ""
  34. Public Sub RefreshUi()
  35. End Sub
  36. '工作线程刷新
  37. Public Sub RefreshWorker()
  38. End Sub
  39. #End Region
  40. #Region "发送请求"
  41. ''' <summary>
  42. ''' 发送 Portsub 请求并等待获取控制台端口。进度将从 0 变化至 80%。
  43. ''' </summary>
  44. Private Shared Sub SendPortsubRequest(User As LinkUserIoi)
  45. End Sub
  46. ''' <summary>
  47. ''' 向控制台发送 Connect 请求。
  48. ''' </summary>
  49. Private Shared Sub SendConnectRequest(User As LinkUserIoi)
  50. Dim RawJson As New JObject()
  51. RawJson("version") = RequestVersion
  52. RawJson("name") = GetPlayerName()
  53. RawJson("id") = IoiId
  54. RawJson("type") = "connect"
  55. User.Send(RawJson)
  56. End Sub
  57. ''' <summary>
  58. ''' 向控制台发送 Update 请求。
  59. ''' </summary>
  60. Private Shared Sub SendUpdateRequest(User As LinkUserIoi, Stage As Integer, Optional Unique As Long = -1)
  61. If Unique = -1 Then Unique = GetTimeTick()
  62. Dim RawJson As New JObject
  63. RawJson("name") = GetPlayerName()
  64. RawJson("id") = IoiId
  65. RawJson("type") = "update"
  66. RawJson("stage") = Stage
  67. RawJson("unique") = Unique
  68. If Stage < 3 Then
  69. Dim Rooms As New JArray
  70. For Each Room In RoomListForMe
  71. Dim RoomObject As New JObject
  72. RoomObject("name") = Room.DisplayName
  73. RoomObject("port") = Room.Port
  74. Rooms.Add(RoomObject)
  75. Next
  76. RawJson("rooms") = Rooms
  77. User.PingPending(Unique) = Date.Now
  78. End If
  79. User.Send(RawJson)
  80. End Sub
  81. ''' <summary>
  82. ''' 尝试发送断开请求,并将其从用户列表中移除。
  83. ''' </summary>
  84. Private Shared Sub SendDisconnectRequest(User As LinkUserIoi, Optional Message As String = Nothing, Optional IsError As Boolean = False)
  85. End Sub
  86. #End Region
  87. #Region "左边栏操作"
  88. '刷新连接
  89. Private Shared Sub BtnListRefresh_Click(sender As MyIconButton, e As EventArgs)
  90. End Sub
  91. '断开连接
  92. Private Shared Sub BtnListDisconnect_Click(sender As MyIconButton, e As EventArgs)
  93. End Sub
  94. '复制联机码
  95. Public Shared Sub BtnLeftCopy_Click() Handles BtnLeftCopy.Click
  96. ClipboardSet(IoiId.Substring(4) & SecretEncrypt(GetPlayerName), False)
  97. Hint("已复制联机码!", HintType.Finish)
  98. End Sub
  99. #End Region
  100. #Region "玩家名"
  101. ''' <summary>
  102. ''' 获取当前的玩家名。
  103. ''' </summary>
  104. Public Shared Function GetPlayerName() As String
  105. '自动生成玩家名
  106. If AutogenPlayerName Is Nothing Then
  107. If IsPlayerNameValid(McLoginName) Then
  108. AutogenPlayerName = McLoginName()
  109. Else
  110. AutogenPlayerName = "玩家 " & CType(GetHash(If(UniqueAddress, "")) Mod 1048576, Integer).ToString("x5").ToUpper
  111. End If
  112. End If
  113. '获取玩家自定义的名称
  114. Dim CustomName As String = Setup.Get("LinkName").ToString.Trim()
  115. If CustomName <> "" Then
  116. If IsPlayerNameValid(CustomName) Then
  117. Return CustomName.Trim
  118. Else
  119. Hint("你所设置的玩家名存在异常,已被重置!", HintType.Critical)
  120. Setup.Set("LinkName", "")
  121. End If
  122. End If
  123. '使用自动生成的玩家名
  124. Return AutogenPlayerName
  125. End Function
  126. Private Shared AutogenPlayerName As String = Nothing '并非由玩家自定义,而是自动生成的玩家名
  127. ''' <summary>
  128. ''' 检查某个玩家名是否合法。
  129. ''' </summary>
  130. Private Shared Function IsPlayerNameValid(Name As String) As Boolean
  131. Return True
  132. End Function
  133. #End Region
  134. #Region "请求核心"
  135. ''' <summary>
  136. ''' 启动 Socket 监听核心。
  137. ''' </summary>
  138. Public Shared Sub StartSocketListener()
  139. End Sub
  140. #End Region
  141. #Region "用户核心"
  142. '用户基类
  143. Public MustInherit Class LinkUserBase
  144. Implements IDisposable
  145. '基础数据
  146. Public Uuid As Integer = GetUuid()
  147. Public Id As String
  148. Public DisplayName As String
  149. '请求管理
  150. Public Socket As Socket = Nothing
  151. Public Sub Send(Request As JObject)
  152. End Sub
  153. Public ListenerThread As Thread = Nothing
  154. Public Sub StartListener()
  155. End Sub
  156. Public Sub BindSocket(Socket As Socket)
  157. If Me.Socket IsNot Nothing Then Throw New Exception("该用户已经绑定了 Socket")
  158. Me.Socket = Socket
  159. StartListener()
  160. End Sub
  161. 'Ping
  162. '0:与 Ping 计算无关,不回应
  163. '1:A to B,2:B to A,3:A to B
  164. Public PingPending As New Dictionary(Of Long, Date)
  165. Public PingRecord As New Queue(Of Integer)
  166. '心跳包
  167. Public LastSend As Date = Date.Now
  168. Public LastReceive As Date = Date.Now
  169. '类型转换
  170. Public Sub New(Id As String, DisplayName As String)
  171. Me.Id = Id
  172. Me.DisplayName = DisplayName
  173. Log("[IOI] 无通信包的新用户对象:" & ToString())
  174. End Sub
  175. Public Sub New(Id As String, DisplayName As String, Socket As Socket)
  176. Me.Id = Id
  177. Me.DisplayName = DisplayName
  178. Me.Socket = Socket
  179. Log("[IOI] 新用户对象:" & ToString())
  180. StartListener()
  181. End Sub
  182. Public Overrides Function ToString() As String
  183. Return DisplayName & " @ " & Id & " #" & Uuid
  184. End Function
  185. Public Shared Widening Operator CType(User As LinkUserBase) As String
  186. Return User.ToString
  187. End Operator
  188. '释放资源
  189. Public IsDisposed As Boolean = False
  190. Protected Overridable Sub Dispose(IsDisposing As Boolean)
  191. If Socket IsNot Nothing Then Socket.Dispose()
  192. If ListenerThread IsNot Nothing AndAlso ListenerThread.IsAlive Then ListenerThread.Interrupt()
  193. End Sub
  194. Public Sub Dispose() Implements IDisposable.Dispose
  195. If Not IsDisposed Then
  196. IsDisposed = True
  197. Dispose(True)
  198. End If
  199. GC.SuppressFinalize(Me)
  200. End Sub
  201. End Class
  202. '用户对象
  203. Public Shared UserList As New Dictionary(Of String, LinkUserIoi)
  204. Public Class LinkUserIoi
  205. Inherits LinkUserBase
  206. Public Sub New(Id As String, DisplayName As String, Socket As Socket)
  207. MyBase.New(Id, DisplayName, Socket)
  208. End Sub
  209. Public Sub New(Id As String, DisplayName As String)
  210. MyBase.New(Id, DisplayName)
  211. End Sub
  212. '基础数据
  213. Public Ports As New Dictionary(Of Integer, String)
  214. Public Rooms As New List(Of RoomEntry)
  215. '进度与 UI
  216. Public Progress As Double = 0
  217. Public RelativeThread As Thread = Nothing
  218. Public Function GetDescription() As String
  219. Return If(Progress < 1,
  220. "正在连接," & Math.Round(Progress * 100) & "%",
  221. "已连接," & If(Not PingRecord.Any(), "检查延迟中", Math.Round(PingRecord.Average) & "ms"))
  222. End Function
  223. Public Function ToListItem() As MyListItem
  224. Dim Item As New MyListItem With {
  225. .Title = DisplayName, .Height = 42, .Tag = Me, .Type = MyListItem.CheckType.None,
  226. .Logo = "pack://application:,,,/images/Blocks/Grass.png"}
  227. '绑定图标按钮
  228. Dim BtnRefresh As New MyIconButton With {.Logo = Logo.IconButtonRefresh, .LogoScale = 0.85, .ToolTip = "刷新", .Tag = Me}
  229. AddHandler BtnRefresh.Click, AddressOf BtnListRefresh_Click
  230. ToolTipService.SetPlacement(BtnRefresh, Primitives.PlacementMode.Bottom)
  231. ToolTipService.SetHorizontalOffset(BtnRefresh, -10)
  232. ToolTipService.SetVerticalOffset(BtnRefresh, 5)
  233. ToolTipService.SetInitialShowDelay(BtnRefresh, 200)
  234. Dim BtnClose As New MyIconButton With {.Logo = Logo.IconButtonCross, .LogoScale = 0.85, .ToolTip = "断开", .Tag = Me}
  235. AddHandler BtnClose.Click, AddressOf BtnListDisconnect_Click
  236. ToolTipService.SetPlacement(BtnClose, Primitives.PlacementMode.Bottom)
  237. ToolTipService.SetHorizontalOffset(BtnClose, -10)
  238. ToolTipService.SetVerticalOffset(BtnClose, 5)
  239. ToolTipService.SetInitialShowDelay(BtnClose, 200)
  240. Item.Buttons = {BtnRefresh, BtnClose}
  241. '刷新并返回
  242. RefreshUi(Item)
  243. Return Item
  244. End Function
  245. Public Sub RefreshUi(RelatedListItem As MyListItem)
  246. RelatedListItem.Title = DisplayName
  247. RelatedListItem.Info = GetDescription()
  248. RelatedListItem.Buttons(0).Visibility = If(Progress = 1, Visibility.Visible, Visibility.Collapsed)
  249. End Sub
  250. '释放
  251. Protected Overrides Sub Dispose(IsDisposing As Boolean)
  252. Log("[IOI] 用户资源释放(IOI, " & DisplayName & ")")
  253. If RelativeThread IsNot Nothing AndAlso RelativeThread.IsAlive Then RelativeThread.Interrupt()
  254. UserList.Remove(Id)
  255. MyBase.Dispose(IsDisposing)
  256. End Sub
  257. End Class
  258. '房间对象
  259. Private Shared RoomListForMe As New List(Of RoomEntry)
  260. Private Function GetRoomList() As List(Of RoomEntry)
  261. Dim RoomList As New List(Of RoomEntry)(RoomListForMe)
  262. For i = 0 To UserList.Count - 1
  263. If i > UserList.Count - 1 Then Exit For
  264. RoomList.AddRange(UserList.Values(i).Rooms)
  265. Next
  266. Return RoomList
  267. End Function
  268. Public Class RoomEntry
  269. '基础数据
  270. Public Port As Integer
  271. Public DisplayName As String
  272. Public User As LinkUserIoi = Nothing '若 IsOwner = True,则此项为 Nothing
  273. Public IsOwner As Boolean
  274. Public ReadOnly Property Ip As String
  275. Get
  276. If IsOwner Then
  277. Return "localhost:" & Port
  278. Else
  279. Return User.Ports(Port) & ":" & Port
  280. End If
  281. End Get
  282. End Property
  283. '类型转换
  284. Public Sub New(Port As Integer, DisplayName As String, Optional User As LinkUserIoi = Nothing)
  285. Me.IsOwner = User Is Nothing
  286. Me.User = User
  287. Me.DisplayName = DisplayName
  288. Me.Port = Port
  289. End Sub
  290. Public Overrides Function ToString() As String
  291. Return DisplayName & " - " & Port & " - " & IsOwner
  292. End Function
  293. Public Shared Widening Operator CType(Room As RoomEntry) As String
  294. Return Room.ToString
  295. End Operator
  296. Public Shared Function SelectPort(Room As RoomEntry) As Integer
  297. Return Room.Port
  298. End Function
  299. 'UI
  300. Public Function GetDescription() As String
  301. If IsOwner Then
  302. Return "由我创建,端口 " & Port
  303. Else
  304. Return "由 " & User.DisplayName & " 创建,端口 " & Port
  305. End If
  306. End Function
  307. Public Function ToListItem() As MyListItem
  308. Dim Item As New MyListItem With {
  309. .Title = DisplayName, .Height = 42, .Info = GetDescription(), .Tag = Me,
  310. .Type = If(IsOwner, MyListItem.CheckType.None, MyListItem.CheckType.Clickable),
  311. .Logo = "pack://application:,,,/images/Blocks/" & If(IsOwner, "GrassPath", "Grass") & ".png"}
  312. If IsOwner Then
  313. '绑定图标按钮
  314. Dim BtnEdit As New MyIconButton With {.Logo = Logo.IconButtonEdit, .LogoScale = 1, .ToolTip = "修改名称", .Tag = Me}
  315. AddHandler BtnEdit.Click, AddressOf BtnRoomEdit_Click
  316. ToolTipService.SetPlacement(BtnEdit, Primitives.PlacementMode.Bottom)
  317. ToolTipService.SetHorizontalOffset(BtnEdit, -22)
  318. ToolTipService.SetVerticalOffset(BtnEdit, 5)
  319. ToolTipService.SetInitialShowDelay(BtnEdit, 200)
  320. Dim BtnClose As New MyIconButton With {.Logo = Logo.IconButtonCross, .LogoScale = 0.85, .ToolTip = "关闭", .Tag = Me}
  321. AddHandler BtnClose.Click, AddressOf BtnRoomClose_Click
  322. ToolTipService.SetPlacement(BtnClose, Primitives.PlacementMode.Bottom)
  323. ToolTipService.SetHorizontalOffset(BtnClose, -10)
  324. ToolTipService.SetVerticalOffset(BtnClose, 5)
  325. ToolTipService.SetInitialShowDelay(BtnClose, 200)
  326. Item.Buttons = {BtnEdit, BtnClose}
  327. Else
  328. '绑定点击事件
  329. AddHandler Item.Click, AddressOf BtnRoom_Click
  330. End If
  331. Return Item
  332. End Function
  333. Public Sub RefreshUi(RelatedListItem As MyListItem)
  334. RelatedListItem.Title = DisplayName
  335. RelatedListItem.Info = GetDescription()
  336. End Sub
  337. End Class
  338. #End Region
  339. '正向与反向连接
  340. Public Shared Sub BtnLeftCreate_Click() Handles BtnLeftCreate.Click
  341. End Sub
  342. Private Shared Sub SendPortsubBack(User As LinkUserIoi, TargetVersion As Integer)
  343. End Sub
  344. '创建房间
  345. Private Sub LinkCreate() Handles BtnCreate.Click
  346. End Sub
  347. Private Shared Sub SendUpdateRequestToAllUsers()
  348. For i = 0 To UserList.Count - 1
  349. If i > UserList.Count - 1 Then Exit For
  350. Dim User = UserList.Values(i)
  351. If User.Progress < 1 Then Continue For
  352. Try
  353. SendUpdateRequest(User, 1) '不需要使用多线程,发送实际会瞬间完成
  354. Catch ex As Exception
  355. Log(ex, "发送全局刷新请求失败(" & User.DisplayName & ")")
  356. End Try
  357. Next
  358. End Sub
  359. '修改房间名称
  360. Private Shared Sub BtnRoomEdit_Click(sender As MyIconButton, e As EventArgs)
  361. End Sub
  362. '加入房间
  363. Private Shared Sub BtnRoom_Click(sender As MyListItem, e As EventArgs)
  364. Dim Room As RoomEntry = sender.Tag
  365. If MyMsgBox("请在多人游戏页面点击直接连接,输入 " & Room.Ip & " 以进入服务器!", "加入房间", "复制地址", "确定") = 1 Then
  366. ClipboardSet(Room.Ip)
  367. End If
  368. End Sub
  369. '关闭房间
  370. Private Shared Sub BtnRoomClose_Click(sender As MyIconButton, e As EventArgs)
  371. End Sub
  372. '获取数据包
  373. Public Shared Sub ReceiveJson(JsonData As JObject, Optional NewSocket As Socket = Nothing)
  374. '获取数据
  375. Dim Id As String = JsonData("id"), Type As String = JsonData("type")
  376. Select Case Type
  377. Case "connect"
  378. Dim DisplayName As String = JsonData("name")
  379. Dim User As New LinkUserIoi(Id, DisplayName, NewSocket)
  380. '如果发生了双向连接
  381. If UserList.ContainsKey(Id) Then
  382. If Id > IoiId Then
  383. Log("[IOI] 双向连接,应当抛弃当前用户(" & DisplayName & ")")
  384. For Each Pair In UserList(User.Id).Ports.ToList
  385. User.Ports(Pair.Key) = Pair.Value
  386. Next
  387. UserList(Id).Dispose()
  388. Else
  389. '应当保留当前用户
  390. Log("[IOI] 双向连接,应当保留当前用户(" & DisplayName & ")")
  391. NewSocket.Dispose()
  392. Exit Sub
  393. End If
  394. End If
  395. '加入列表
  396. UserList.Add(Id, User)
  397. '返回请求
  398. User.RelativeThread = RunInNewThread(Sub()
  399. SendPortsubBack(User, JsonData("version").ToObject(Of Integer))
  400. End Sub, "Link Connect " & DisplayName)
  401. '更新时间
  402. User.LastReceive = Date.Now
  403. Case "update"
  404. If Not UserList.ContainsKey(Id) Then Throw New Exception("未在列表中的用户发送了更新请求:" & Id)
  405. Dim User = UserList(Id)
  406. '拉满进度(该请求也作为反向连接回应出现,用于向正向连接方传达连接已完成信号)
  407. User.Progress = 1
  408. '更新名称
  409. Dim DisplayName As String = JsonData("name")
  410. User.DisplayName = DisplayName
  411. '更新房间列表
  412. If JsonData("rooms") IsNot Nothing Then
  413. User.Rooms = New List(Of RoomEntry)
  414. For Each RoomObject In JsonData("rooms")
  415. User.Rooms.Add(New RoomEntry(RoomObject("port"), RoomObject("name"), User))
  416. Next
  417. End If
  418. '更新 Ping
  419. Dim Stage As Integer = JsonData("stage"), Unique As Long = JsonData("unique")
  420. If Stage > 1 Then
  421. User.PingRecord.Enqueue((Date.Now - User.PingPending(Unique)).TotalMilliseconds / 2)
  422. If User.PingRecord.Count > 5 Then User.PingRecord.Dequeue()
  423. User.PingPending.Remove(Unique)
  424. End If
  425. '返回请求
  426. If Stage > 0 AndAlso Stage < 3 Then RunInNewThread(Sub()
  427. Try
  428. SendUpdateRequest(User, Stage + 1, Unique)
  429. Catch ex As Exception
  430. Log(ex, "发送回程请求失败")
  431. End Try
  432. End Sub, "Link Update " & DisplayName)
  433. '更新时间
  434. User.LastReceive = Date.Now
  435. Case "disconnect"
  436. '断开连接
  437. If Not UserList.ContainsKey(Id) Then Exit Sub
  438. UserRemove(UserList(Id), ShowLeaveMessage:=JsonData("message") Is Nothing)
  439. If JsonData("message") IsNot Nothing Then Hint(JsonData("message").ToString, If(JsonData("isError").ToObject(Of Boolean), HintType.Critical, HintType.Info))
  440. Case Else
  441. Throw New Exception("未知的操作种类:" & Type)
  442. End Select
  443. End Sub
  444. ''' <summary>
  445. ''' 从用户列表中移除一位用户。提示信息视作该用户主动离开。
  446. ''' </summary>
  447. Public Shared Sub UserRemove(User As LinkUserIoi, ShowLeaveMessage As Boolean)
  448. End Sub
  449. Public Shared Sub ModuleStopManually()
  450. End Sub
  451. End Class