16_Chat.lua 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. -- Identifier for the chat network messages
  7. local MSG_CHAT = 32
  8. -- UDP port we will use
  9. local CHAT_SERVER_PORT = 2345
  10. local chatHistory = {}
  11. local chatHistoryText = nil
  12. local buttonContainer = nil
  13. local textEdit = nil
  14. local sendButton = nil
  15. local connectButton = nil
  16. local disconnectButton = nil
  17. local startServerButton = nil
  18. function Start()
  19. -- Execute the common startup for samples
  20. SampleStart()
  21. -- Enable OS cursor
  22. input.mouseVisible = true
  23. -- Create the user interface
  24. CreateUI()
  25. -- Subscribe to UI and network events
  26. SubscribeToEvents()
  27. end
  28. function CreateUI()
  29. SetLogoVisible(false) -- We need the full rendering window
  30. local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
  31. -- Set style to the UI root so that elements will inherit it
  32. ui.root.defaultStyle = uiStyle
  33. local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
  34. chatHistoryText = ui.root:CreateChild("Text")
  35. chatHistoryText:SetFont(font, 12)
  36. buttonContainer = ui.root:CreateChild("UIElement")
  37. buttonContainer:SetFixedSize(graphics.width, 20)
  38. buttonContainer:SetPosition(0, graphics.height - 20)
  39. buttonContainer.layoutMode = LM_HORIZONTAL
  40. textEdit = buttonContainer:CreateChild("LineEdit")
  41. textEdit:SetStyleAuto()
  42. sendButton = CreateButton("Send", 70)
  43. connectButton = CreateButton("Connect", 90)
  44. disconnectButton = CreateButton("Disconnect", 100)
  45. startServerButton = CreateButton("Start Server", 110)
  46. UpdateButtons()
  47. local size = (graphics.height - 20) / chatHistoryText.rowHeight
  48. for i = 1, size do
  49. table.insert(chatHistory, "")
  50. end
  51. -- No viewports or scene is defined. However, the default zone's fog color controls the fill color
  52. renderer.defaultZone.fogColor = Color(0.0, 0.0, 0.1)
  53. end
  54. function SubscribeToEvents()
  55. -- Subscribe to UI element events
  56. SubscribeToEvent(textEdit, "TextFinished", "HandleSend")
  57. SubscribeToEvent(sendButton, "Released", "HandleSend")
  58. SubscribeToEvent(connectButton, "Released", "HandleConnect")
  59. SubscribeToEvent(disconnectButton, "Released", "HandleDisconnect")
  60. SubscribeToEvent(startServerButton, "Released", "HandleStartServer")
  61. -- Subscribe to log messages so that we can pipe them to the chat window
  62. SubscribeToEvent("LogMessage", "HandleLogMessage")
  63. -- Subscribe to network events
  64. SubscribeToEvent("NetworkMessage", "HandleNetworkMessage")
  65. SubscribeToEvent("ServerConnected", "HandleConnectionStatus")
  66. SubscribeToEvent("ServerDisconnected", "HandleConnectionStatus")
  67. SubscribeToEvent("ConnectFailed", "HandleConnectionStatus")
  68. end
  69. function CreateButton(text, width)
  70. local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
  71. local button = buttonContainer:CreateChild("Button")
  72. button:SetStyleAuto()
  73. button:SetFixedWidth(width)
  74. local buttonText = button:CreateChild("Text")
  75. buttonText:SetFont(font, 12)
  76. buttonText:SetAlignment(HA_CENTER, VA_CENTER)
  77. buttonText.text = text
  78. return button
  79. end
  80. function ShowChatText(row)
  81. table.remove(chatHistory, 1)
  82. table.insert(chatHistory, row)
  83. -- Concatenate all the rows in history
  84. local allRows = ""
  85. for i, r in ipairs(chatHistory) do
  86. allRows = allRows .. r .. "\n"
  87. end
  88. chatHistoryText.text = allRows
  89. end
  90. function UpdateButtons()
  91. local serverConnection = network.serverConnection
  92. local serverRunning = network.serverRunning
  93. -- Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
  94. sendButton.visible = serverConnection ~= nil
  95. connectButton.visible = (serverConnection == nil) and (not serverRunning)
  96. disconnectButton.visible = (serverConnection ~= nil) or serverRunning
  97. startServerButton.visible = (serverConnection == nil) and (not serverRunning)
  98. end
  99. function HandleLogMessage(eventType, eventData)
  100. ShowChatText(eventData:GetString("Message"))
  101. end
  102. function HandleSend(eventType, eventData)
  103. local text = textEdit.text
  104. if text == "" then
  105. return -- Do not send an empty message
  106. end
  107. local serverConnection = network.serverConnection
  108. if serverConnection ~= nil then
  109. -- A VectorBuffer object is convenient for constructing a message to send
  110. local msg = VectorBuffer()
  111. msg:WriteString(text)
  112. -- Send the chat message as in-order and reliable
  113. serverConnection:SendMessage(MSG_CHAT, true, true, msg)
  114. -- Empty the text edit after sending
  115. textEdit.text = ""
  116. end
  117. end
  118. function HandleConnect(eventType, eventData)
  119. local address = textEdit.text
  120. if address == "" then
  121. address = "localhost" -- Use localhost to connect if nothing else specified
  122. end
  123. -- Empty the text edit after reading the address to connect to
  124. textEdit.text = ""
  125. -- Connect to server, do not specify a client scene as we are not using scene replication, just messages.
  126. -- At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
  127. -- case we skip it for simplicity
  128. network:Connect(address, CHAT_SERVER_PORT, nil)
  129. UpdateButtons()
  130. end
  131. function HandleDisconnect(eventType, eventData)
  132. local serverConnection = network.serverConnection
  133. -- If we were connected to server, disconnect
  134. if serverConnection ~= nil then
  135. serverConnection:Disconnect()
  136. -- Or if we were running a server, stop it
  137. else
  138. if network.serverRunning then
  139. network:StopServer()
  140. end
  141. end
  142. UpdateButtons()
  143. end
  144. function HandleStartServer(eventType, eventData)
  145. network:StartServer(CHAT_SERVER_PORT)
  146. UpdateButtons()
  147. end
  148. function HandleNetworkMessage(eventType, eventData)
  149. local msgID = eventData:GetInt("MessageID")
  150. if msgID == MSG_CHAT then
  151. local msg = eventData:GetBuffer("Data")
  152. local text = msg:ReadString()
  153. -- If we are the server, prepend the sender's IP address and port and echo to everyone
  154. -- If we are a client, just display the message
  155. if network.serverRunning then
  156. local sender = eventData:GetPtr("Connection", "Connection")
  157. text = sender:ToString() .. " " .. text
  158. local sendMsg = VectorBuffer()
  159. sendMsg:WriteString(text)
  160. -- Broadcast as in-order and reliable
  161. network:BroadcastMessage(MSG_CHAT, true, true, sendMsg)
  162. end
  163. ShowChatText(text)
  164. end
  165. end
  166. function HandleConnectionStatus(eventType, eventData)
  167. UpdateButtons()
  168. end
  169. -- Create XML patch instructions for screen joystick layout specific to this sample app
  170. function GetScreenJoystickPatchString()
  171. return
  172. "<patch>" ..
  173. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button2']]\">" ..
  174. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  175. " </add>" ..
  176. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
  177. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  178. " </add>" ..
  179. "</patch>"
  180. end