Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local serverUrl = "ws://84.86.255.191:8765"
- os.loadAPI("json")
- -- State
- state = {}
- state["pos"] = {}
- state["name"] = os.getComputerLabel()
- state["loggedIn"] = false
- state["pos"]["x"] = 0
- state["pos"]["y"] = 0
- state["pos"]["z"] = 0
- state["pos"]["facing"] = "north"
- -- Connect to the WebSocket server
- header = {["device"] = "turtle"}
- local ws, err = assert(http.websocket(serverUrl, header))
- -- Communication functions
- local function sendData(data)
- ws.send(json.encode(data))
- end
- -- Check WebSocket server
- if not ws then
- print("Failed to connect to WebSocket server:", err)
- return
- end
- print("Connected to Server. trying to login...")
- sendData(state)
- -- Receive and handle messages from the WebSocket server
- while true do
- local messageStr, err = ws.receive()
- if messageStr then
- message = json.decode(messageStr)
- if not state.loggedIn then
- state.loggedIn = message.loggedIn
- print(message.message) -- print welcome message from server
- state["message"] = "ready"
- sendData(state)
- else
- -- Load the function from the string
- local loadedFunction = load(message.func)
- -- Check if the loaded object is a function
- if type(loadedFunction) == "function" then
- -- Call the loaded function
- loadedFunction()
- else
- print("Failed to load the function from the string.")
- end
- end
- else
- print("Failed to receive message:", err)
- break
- end
- end
- -- Close the WebSocket connection when done
- ws.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement