16_Chat.lua 7.0 KB

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