16_Chat.lua 7.5 KB

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