52_NATPunchtrough.lua 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. -- Chat example
  2. -- This sample demonstrates:
  3. -- - Starting up a network server or connecting to it
  4. -- - Implementing simple chat functionality with network messages
  5. require "LuaScripts/Utilities/Sample"
  6. local natServerAddress = nil
  7. local natServerPort = nil
  8. local saveNatSettingsButton = nil
  9. local startServerButton = nil
  10. local serverGuid = nil
  11. local connectButton = nil
  12. local logHistory = {}
  13. local logHistoryText = nil
  14. local guid = nil
  15. -- Local server port
  16. local SERVER_PORT = 54654
  17. function Start()
  18. -- Execute the common startup for samples
  19. SampleStart()
  20. -- Enable OS cursor
  21. input.mouseVisible = true
  22. -- Create the user interface
  23. CreateUI()
  24. -- Set the mouse mode to use in the sample
  25. SampleInitMouseMode(MM_FREE)
  26. -- Subscribe to UI and network events
  27. SubscribeToEvents()
  28. end
  29. function CreateUI()
  30. SetLogoVisible(true) -- We need the full rendering window
  31. local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
  32. -- Set style to the UI root so that elements will inherit it
  33. ui.root.defaultStyle = uiStyle
  34. local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
  35. logHistoryText = ui.root:CreateChild("Text")
  36. logHistoryText:SetFont(font, 12)
  37. logHistoryText:SetPosition(20, 200);
  38. local marginTop = 40
  39. CreateLabel("1. Run NAT server somewhere, enter NAT server info and press 'Save NAT settings'", IntVector2(20, marginTop-20));
  40. natServerAddress = CreateLineEdit("127.0.0.1", 200, IntVector2(20, marginTop));
  41. natServerPort = CreateLineEdit("61111", 100, IntVector2(240, marginTop));
  42. saveNatSettingsButton = CreateButton("Save NAT settings", 160, IntVector2(360, marginTop));
  43. marginTop = 120;
  44. CreateLabel("2. Create server and give others your server GUID", IntVector2(20, marginTop-20));
  45. guid = CreateLineEdit("Your server GUID", 200, IntVector2(20, marginTop));
  46. startServerButton = CreateButton("Start server", 160, IntVector2(240, marginTop));
  47. marginTop = 200;
  48. CreateLabel("3. Input local or remote server GUID", IntVector2(20, marginTop-20));
  49. serverGuid = CreateLineEdit("Remote server GUID", 200, IntVector2(20, marginTop));
  50. connectButton = CreateButton("Connect", 160, IntVector2(240, marginTop));
  51. local size = 20
  52. for i = 1, size do
  53. table.insert(logHistory, "")
  54. end
  55. -- No viewports or scene is defined. However, the default zone's fog color controls the fill color
  56. renderer.defaultZone.fogColor = Color(0.0, 0.0, 0.1)
  57. end
  58. function SubscribeToEvents()
  59. SubscribeToEvent("ServerConnected", "HandleServerConnected");
  60. SubscribeToEvent("ServerDisconnected", "HandleServerDisconnected");
  61. SubscribeToEvent("ConnectFailed", "HandleConnectFailed");
  62. -- NAT server connection related events
  63. SubscribeToEvent("NetworkNatMasterConnectionFailed", "HandleNatConnectionFailed");
  64. SubscribeToEvent("NetworkNatMasterConnectionSucceeded", "HandleNatConnectionSucceeded");
  65. -- NAT punchtrough request events
  66. SubscribeToEvent("NetworkNatPunchtroughSucceeded", "HandleNatPunchtroughSucceeded");
  67. SubscribeToEvent("NetworkNatPunchtroughFailed", "HandleNatPunchtroughFailed");
  68. SubscribeToEvent("ClientConnected", "HandleClientConnected");
  69. SubscribeToEvent("ClientDisconnected", "HandleClientDisconnected");
  70. -- Subscribe to UI element events
  71. SubscribeToEvent(saveNatSettingsButton, "Released", "HandleSaveNatSettings");
  72. SubscribeToEvent(startServerButton, "Released", "HandleStartServer");
  73. SubscribeToEvent(connectButton, "Released", "HandleConnect");
  74. end
  75. function CreateButton(text, width, position)
  76. local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
  77. local button = ui.root:CreateChild("Button")
  78. button:SetStyleAuto()
  79. button:SetFixedWidth(width)
  80. button:SetFixedHeight(30)
  81. button:SetPosition(position.x, position.y)
  82. local buttonText = button:CreateChild("Text")
  83. buttonText:SetFont(font, 12)
  84. buttonText:SetAlignment(HA_CENTER, VA_CENTER)
  85. buttonText.text = text
  86. return button
  87. end
  88. function CreateLabel(text, position)
  89. local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
  90. local label = ui.root:CreateChild("Text")
  91. label:SetFont(font, 12)
  92. label.color = Color(0.0, 1.0, 0.0)
  93. label:SetPosition(position.x, position.y)
  94. label.text = text
  95. end
  96. function CreateLineEdit(placeholder, width, position)
  97. local textEdit = ui.root:CreateChild("LineEdit")
  98. textEdit:SetStyleAuto()
  99. textEdit:SetFixedWidth(width)
  100. textEdit:SetFixedHeight(30)
  101. textEdit.text = placeholder
  102. textEdit:SetPosition(position.x, position.y)
  103. return textEdit
  104. end
  105. function ShowLogMessage(row)
  106. table.remove(logHistory, 1)
  107. table.insert(logHistory, row)
  108. -- Concatenate all the rows in history
  109. local allRows = ""
  110. for i, r in ipairs(logHistory) do
  111. allRows = allRows .. r .. "\n"
  112. end
  113. logHistoryText.text = allRows
  114. end
  115. function HandleLogMessage(eventType, eventData)
  116. ShowChatText(eventData["Message"]:GetString())
  117. end
  118. function HandleSaveNatSettings(eventType, eventData)
  119. local address = natServerAddress.text
  120. local port = natServerPort.text
  121. -- Save NAT server configuration
  122. network:SetNATServerInfo(address, port);
  123. ShowLogMessage("Saving NAT settings: " .. address .. ":" .. port);
  124. end
  125. function HandleServerConnected(eventType, eventData)
  126. end
  127. function HandleConnect(eventType, eventData)
  128. local address = textEdit.text
  129. if address == "" then
  130. address = "localhost" -- Use localhost to connect if nothing else specified
  131. end
  132. -- Empty the text edit after reading the address to connect to
  133. textEdit.text = ""
  134. -- Connect to server, do not specify a client scene as we are not using scene replication, just messages.
  135. -- At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
  136. -- case we skip it for simplicity
  137. network:Connect(address, CHAT_SERVER_PORT, nil)
  138. end
  139. function HandleServerConnected(eventType, eventData)
  140. ShowLogMessage("Client: Server connected!");
  141. end
  142. function HandleServerDisconnected(eventType, eventData)
  143. ShowLogMessage("Client: Server disconnected!");
  144. end
  145. function HandleConnectFailed(eventType, eventData)
  146. ShowLogMessage("Client: Connection failed!");
  147. end
  148. function HandleStartServer(eventType, eventData)
  149. network:StartServer(SERVER_PORT);
  150. ShowLogMessage("Server: Server started on port: " .. SERVER_PORT);
  151. -- Connect to the NAT server
  152. network:StartNATClient();
  153. ShowLogMessage("Server: Starting NAT client for server...");
  154. -- Output our assigned GUID which others will use to connect to our server
  155. guid.text = network:GetGUID();
  156. end
  157. function HandleConnect(eventType, eventData)
  158. local userData = VariantMap()
  159. userData["Name"] = "Urho3D";
  160. -- Attempt connecting to server using custom GUID, Scene = null as a second parameter and user identity is passed as third parameter
  161. network:AttemptNATPunchtrough(serverGuid.text, null, userData);
  162. ShowLogMessage("Client: Attempting NAT punchtrough to guid: " + serverGuid.text);
  163. end
  164. function HandleNatConnectionFailed(eventType, eventData)
  165. ShowLogMessage("Connection to NAT master server failed!");
  166. end
  167. function HandleNatConnectionSucceeded(eventType, eventData)
  168. ShowLogMessage("Connection to NAT master server succeeded!");
  169. end
  170. function HandleNatPunchtroughSucceeded(eventType, eventData)
  171. ShowLogMessage("NAT punchtrough succeeded!");
  172. end
  173. function HandleNatPunchtroughFailed(eventType, eventData)
  174. ShowLogMessage("NAT punchtrough failed!");
  175. end
  176. function HandleClientConnected(eventType, eventData)
  177. ShowLogMessage("Server: Client connected!");
  178. end
  179. function HandleClientDisconnected(eventType, eventData)
  180. ShowLogMessage("Server: Client disconnected!");
  181. end
  182. -- Create XML patch instructions for screen joystick layout specific to this sample app
  183. function GetScreenJoystickPatchString()
  184. return
  185. "<patch>" ..
  186. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button2']]\">" ..
  187. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  188. " </add>" ..
  189. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
  190. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  191. " </add>" ..
  192. "</patch>"
  193. end