PageLinkIoi.xaml.vb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. End Sub
  97. #End Region
  98. #Region "玩家名"
  99. ''' <summary>
  100. ''' 获取当前的玩家名。
  101. ''' </summary>
  102. Public Shared Function GetPlayerName() As String
  103. '自动生成玩家名
  104. If AutogenPlayerName Is Nothing Then
  105. If IsPlayerNameValid(McLoginName) Then
  106. AutogenPlayerName = McLoginName()
  107. Else
  108. AutogenPlayerName = "玩家 " & CType(GetHash(If(UniqueAddress, "")) Mod 1048576, Integer).ToString("x5").ToUpper
  109. End If
  110. End If
  111. '获取玩家自定义的名称
  112. Dim CustomName As String = Setup.Get("LinkName").ToString.Trim()
  113. If CustomName <> "" Then
  114. If IsPlayerNameValid(CustomName) Then
  115. Return CustomName.Trim
  116. Else
  117. Hint("你所设置的玩家名存在异常,已被重置!", HintType.Critical)
  118. Setup.Set("LinkName", "")
  119. End If
  120. End If
  121. '使用自动生成的玩家名
  122. Return AutogenPlayerName
  123. End Function
  124. Private Shared AutogenPlayerName As String = Nothing '并非由玩家自定义,而是自动生成的玩家名
  125. ''' <summary>
  126. ''' 检查某个玩家名是否合法。
  127. ''' </summary>
  128. Private Shared Function IsPlayerNameValid(Name As String) As Boolean
  129. Return True
  130. End Function
  131. #End Region
  132. #Region "请求核心"
  133. ''' <summary>
  134. ''' 启动 Socket 监听核心。
  135. ''' </summary>
  136. Public Shared Sub StartSocketListener()
  137. End Sub
  138. #End Region
  139. #Region "用户核心"
  140. '用户基类
  141. Public MustInherit Class LinkUserBase
  142. Implements IDisposable
  143. '基础数据
  144. Public Uuid As Integer = GetUuid()
  145. Public Id As String
  146. Public DisplayName As String
  147. '请求管理
  148. Public Socket As Socket = Nothing
  149. Public Sub Send(Request As JObject)
  150. End Sub
  151. Public ListenerThread As Thread = Nothing
  152. Public Sub StartListener()
  153. End Sub
  154. Public Sub BindSocket(Socket As Socket)
  155. If Me.Socket IsNot Nothing Then Throw New Exception("该用户已经绑定了 Socket")
  156. Me.Socket = Socket
  157. StartListener()
  158. End Sub
  159. 'Ping
  160. '0:与 Ping 计算无关,不回应
  161. '1:A to B,2:B to A,3:A to B
  162. Public PingPending As New Dictionary(Of Long, Date)
  163. Public PingRecord As New Queue(Of Integer)
  164. '心跳包
  165. Public LastSend As Date = Date.Now
  166. Public LastReceive As Date = Date.Now
  167. '类型转换
  168. Public Sub New(Id As String, DisplayName As String)
  169. Me.Id = Id
  170. Me.DisplayName = DisplayName
  171. Log("[IOI] 无通信包的新用户对象:" & ToString())
  172. End Sub
  173. Public Sub New(Id As String, DisplayName As String, Socket As Socket)
  174. Me.Id = Id
  175. Me.DisplayName = DisplayName
  176. Me.Socket = Socket
  177. Log("[IOI] 新用户对象:" & ToString())
  178. StartListener()
  179. End Sub
  180. Public Overrides Function ToString() As String
  181. Return DisplayName & " @ " & Id & " #" & Uuid
  182. End Function
  183. Public Shared Widening Operator CType(User As LinkUserBase) As String
  184. Return User.ToString
  185. End Operator
  186. '释放资源
  187. Public IsDisposed As Boolean = False
  188. Protected Overridable Sub Dispose(IsDisposing As Boolean)
  189. If Socket IsNot Nothing Then Socket.Dispose()
  190. If ListenerThread IsNot Nothing AndAlso ListenerThread.IsAlive Then ListenerThread.Interrupt()
  191. End Sub
  192. Public Sub Dispose() Implements IDisposable.Dispose
  193. If Not IsDisposed Then
  194. IsDisposed = True
  195. Dispose(True)
  196. End If
  197. GC.SuppressFinalize(Me)
  198. End Sub
  199. End Class
  200. '用户对象
  201. Public Shared UserList As New Dictionary(Of String, LinkUserIoi)
  202. Public Class LinkUserIoi
  203. Inherits LinkUserBase
  204. Public Sub New(Id As String, DisplayName As String, Socket As Socket)
  205. MyBase.New(Id, DisplayName, Socket)
  206. End Sub
  207. Public Sub New(Id As String, DisplayName As String)
  208. MyBase.New(Id, DisplayName)
  209. End Sub
  210. '基础数据
  211. Public Ports As New Dictionary(Of Integer, String)
  212. Public Rooms As New List(Of RoomEntry)
  213. '进度与 UI
  214. Public Progress As Double = 0
  215. Public RelativeThread As Thread = Nothing
  216. Public Function GetDescription() As String
  217. Return If(Progress < 1,
  218. "正在连接," & Math.Round(Progress * 100) & "%",
  219. "已连接," & If(Not PingRecord.Any(), "检查延迟中", Math.Round(PingRecord.Average) & "ms"))
  220. End Function
  221. Public Function ToListItem() As MyListItem
  222. Dim Item As New MyListItem With {
  223. .Title = DisplayName, .Height = 42, .Tag = Me, .Type = MyListItem.CheckType.None,
  224. .Logo = "pack://application:,,,/images/Blocks/Grass.png"}
  225. '绑定图标按钮
  226. Dim BtnRefresh As New MyIconButton With {.Logo = Logo.IconButtonRefresh, .LogoScale = 0.85, .ToolTip = "刷新", .Tag = Me}
  227. AddHandler BtnRefresh.Click, AddressOf BtnListRefresh_Click
  228. ToolTipService.SetPlacement(BtnRefresh, Primitives.PlacementMode.Bottom)
  229. ToolTipService.SetHorizontalOffset(BtnRefresh, -10)
  230. ToolTipService.SetVerticalOffset(BtnRefresh, 5)
  231. ToolTipService.SetInitialShowDelay(BtnRefresh, 200)
  232. Dim BtnClose As New MyIconButton With {.Logo = Logo.IconButtonCross, .LogoScale = 0.85, .ToolTip = "断开", .Tag = Me}
  233. AddHandler BtnClose.Click, AddressOf BtnListDisconnect_Click
  234. ToolTipService.SetPlacement(BtnClose, Primitives.PlacementMode.Bottom)
  235. ToolTipService.SetHorizontalOffset(BtnClose, -10)
  236. ToolTipService.SetVerticalOffset(BtnClose, 5)
  237. ToolTipService.SetInitialShowDelay(BtnClose, 200)
  238. Item.Buttons = {BtnRefresh, BtnClose}
  239. '刷新并返回
  240. RefreshUi(Item)
  241. Return Item
  242. End Function
  243. Public Sub RefreshUi(RelatedListItem As MyListItem)
  244. RelatedListItem.Title = DisplayName
  245. RelatedListItem.Info = GetDescription()
  246. RelatedListItem.Buttons(0).Visibility = If(Progress = 1, Visibility.Visible, Visibility.Collapsed)
  247. End Sub
  248. '释放
  249. Protected Overrides Sub Dispose(IsDisposing As Boolean)
  250. Log("[IOI] 用户资源释放(IOI, " & DisplayName & ")")
  251. If RelativeThread IsNot Nothing AndAlso RelativeThread.IsAlive Then RelativeThread.Interrupt()
  252. UserList.Remove(Id)
  253. MyBase.Dispose(IsDisposing)
  254. End Sub
  255. End Class
  256. '房间对象
  257. Private Shared RoomListForMe As New List(Of RoomEntry)
  258. Private Function GetRoomList() As List(Of RoomEntry)
  259. Dim RoomList As New List(Of RoomEntry)(RoomListForMe)
  260. For i = 0 To UserList.Count - 1
  261. If i > UserList.Count - 1 Then Exit For
  262. RoomList.AddRange(UserList.Values(i).Rooms)
  263. Next
  264. Return RoomList
  265. End Function
  266. Public Class RoomEntry
  267. '基础数据
  268. Public Port As Integer
  269. Public DisplayName As String
  270. Public User As LinkUserIoi = Nothing '若 IsOwner = True,则此项为 Nothing
  271. Public IsOwner As Boolean
  272. Public ReadOnly Property Ip As String
  273. Get
  274. If IsOwner Then
  275. Return "localhost:" & Port
  276. Else
  277. Return User.Ports(Port) & ":" & Port
  278. End If
  279. End Get
  280. End Property
  281. '类型转换
  282. Public Sub New(Port As Integer, DisplayName As String, Optional User As LinkUserIoi = Nothing)
  283. Me.IsOwner = User Is Nothing
  284. Me.User = User
  285. Me.DisplayName = DisplayName
  286. Me.Port = Port
  287. End Sub
  288. Public Overrides Function ToString() As String
  289. Return DisplayName & " - " & Port & " - " & IsOwner
  290. End Function
  291. Public Shared Widening Operator CType(Room As RoomEntry) As String
  292. Return Room.ToString
  293. End Operator
  294. Public Shared Function SelectPort(Room As RoomEntry) As Integer
  295. Return Room.Port
  296. End Function
  297. 'UI
  298. Public Function GetDescription() As String
  299. If IsOwner Then
  300. Return "由我创建,端口 " & Port
  301. Else
  302. Return "由 " & User.DisplayName & " 创建,端口 " & Port
  303. End If
  304. End Function
  305. Public Function ToListItem() As MyListItem
  306. Dim Item As New MyListItem With {
  307. .Title = DisplayName, .Height = 42, .Info = GetDescription(), .Tag = Me,
  308. .Type = If(IsOwner, MyListItem.CheckType.None, MyListItem.CheckType.Clickable),
  309. .Logo = "pack://application:,,,/images/Blocks/" & If(IsOwner, "GrassPath", "Grass") & ".png"}
  310. If IsOwner Then
  311. '绑定图标按钮
  312. Dim BtnEdit As New MyIconButton With {.Logo = Logo.IconButtonEdit, .LogoScale = 1, .ToolTip = "修改名称", .Tag = Me}
  313. AddHandler BtnEdit.Click, AddressOf BtnRoomEdit_Click
  314. ToolTipService.SetPlacement(BtnEdit, Primitives.PlacementMode.Bottom)
  315. ToolTipService.SetHorizontalOffset(BtnEdit, -22)
  316. ToolTipService.SetVerticalOffset(BtnEdit, 5)
  317. ToolTipService.SetInitialShowDelay(BtnEdit, 200)
  318. Dim BtnClose As New MyIconButton With {.Logo = Logo.IconButtonCross, .LogoScale = 0.85, .ToolTip = "关闭", .Tag = Me}
  319. AddHandler BtnClose.Click, AddressOf BtnRoomClose_Click
  320. ToolTipService.SetPlacement(BtnClose, Primitives.PlacementMode.Bottom)
  321. ToolTipService.SetHorizontalOffset(BtnClose, -10)
  322. ToolTipService.SetVerticalOffset(BtnClose, 5)
  323. ToolTipService.SetInitialShowDelay(BtnClose, 200)
  324. Item.Buttons = {BtnEdit, BtnClose}
  325. Else
  326. '绑定点击事件
  327. AddHandler Item.Click, AddressOf BtnRoom_Click
  328. End If
  329. Return Item
  330. End Function
  331. Public Sub RefreshUi(RelatedListItem As MyListItem)
  332. RelatedListItem.Title = DisplayName
  333. RelatedListItem.Info = GetDescription()
  334. End Sub
  335. End Class
  336. #End Region
  337. '正向与反向连接
  338. Public Shared Sub BtnLeftCreate_Click() Handles BtnLeftCreate.Click
  339. End Sub
  340. Private Shared Sub SendPortsubBack(User As LinkUserIoi, TargetVersion As Integer)
  341. End Sub
  342. '创建房间
  343. Private Sub LinkCreate() Handles BtnCreate.Click
  344. End Sub
  345. Private Shared Sub SendUpdateRequestToAllUsers()
  346. For i = 0 To UserList.Count - 1
  347. If i > UserList.Count - 1 Then Exit For
  348. Dim User = UserList.Values(i)
  349. If User.Progress < 1 Then Continue For
  350. Try
  351. SendUpdateRequest(User, 1) '不需要使用多线程,发送实际会瞬间完成
  352. Catch ex As Exception
  353. Log(ex, "发送全局刷新请求失败(" & User.DisplayName & ")")
  354. End Try
  355. Next
  356. End Sub
  357. '修改房间名称
  358. Private Shared Sub BtnRoomEdit_Click(sender As MyIconButton, e As EventArgs)
  359. End Sub
  360. '加入房间
  361. Private Shared Sub BtnRoom_Click(sender As MyListItem, e As EventArgs)
  362. Dim Room As RoomEntry = sender.Tag
  363. If MyMsgBox("请在多人游戏页面点击直接连接,输入 " & Room.Ip & " 以进入服务器!", "加入房间", "复制地址", "确定") = 1 Then
  364. ClipboardSet(Room.Ip)
  365. End If
  366. End Sub
  367. '关闭房间
  368. Private Shared Sub BtnRoomClose_Click(sender As MyIconButton, e As EventArgs)
  369. End Sub
  370. '获取数据包
  371. Public Shared Sub ReceiveJson(JsonData As JObject, Optional NewSocket As Socket = Nothing)
  372. End Sub
  373. ''' <summary>
  374. ''' 从用户列表中移除一位用户。提示信息视作该用户主动离开。
  375. ''' </summary>
  376. Public Shared Sub UserRemove(User As LinkUserIoi, ShowLeaveMessage As Boolean)
  377. End Sub
  378. Public Shared Sub ModuleStopManually()
  379. End Sub
  380. End Class