2
0

16_Chat.lua 7.1 KB

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