WebSocket

HTML5 与 WebSocket

WebSocket协议在2011年被标准化, 最初的目标是让浏览器与服务器建立稳定的双向连接. 在此之前, 浏览器曾只支持HTTPRequests, 并不适合双向通信.

The protocol is message based and a very powerful tool to send push notifications to browsers, and has been used to implement chats, turn-based games, etc. It still uses a TCP connection, which is good for reliability but not for latency, so not good for real-time applications like VoIP and fast-paced games (see WebRTC for those use cases).

由于它的简单性, 广泛的兼容性以及比原始TCP连接更容易使用,WebSocket很快就开始在浏览器以外的地方应用, 在本地应用程序中作为与网络服务器通信的一种手段.

Godot在本机和HTML5导出中都支持WebSocket.

在 Godot 中使用 WebSocket

WebSocket is implemented in Godot via WebSocketPeer. The WebSocket implementation is compatible with the High Level Multiplayer. See section on high-level multiplayer for more details.

警告

导出到 Android 时,在导出项目或使用一键部署之前,确保在 Android 导出预设中启用 INTERNET 权限。否则,Android 系统会阻止该程序任何形式的网络通信。

最小客户端示例

本示例将向你展示如何创建与远程服务器的 WebSocket 连接, 以及如何发送和接收数据.

  1. extends Node
  2. # The URL we will connect to.
  3. @export var websocket_url = "wss://echo.websocket.org"
  4. # Our WebSocketClient instance.
  5. var socket = WebSocketPeer.new()
  6. func _ready():
  7. # Initiate connection to the given URL.
  8. var err = socket.connect_to_url(websocket_url)
  9. if err != OK:
  10. print("Unable to connect")
  11. set_process(false)
  12. else:
  13. # Wait for the socket to connect.
  14. await get_tree().create_timer(2).timeout
  15. # Send data.
  16. socket.send_text("Test packet")
  17. func _process(_delta):
  18. # Call this in _process or _physics_process. Data transfer and state updates
  19. # will only happen when calling this function.
  20. socket.poll()
  21. # get_ready_state() tells you what state the socket is in.
  22. var state = socket.get_ready_state()
  23. # WebSocketPeer.STATE_OPEN means the socket is connected and ready
  24. # to send and receive data.
  25. if state == WebSocketPeer.STATE_OPEN:
  26. while socket.get_available_packet_count():
  27. print("Got data from server: ", socket.get_packet().get_string_from_utf8())
  28. # WebSocketPeer.STATE_CLOSING means the socket is closing.
  29. # It is important to keep polling for a clean close.
  30. elif state == WebSocketPeer.STATE_CLOSING:
  31. pass
  32. # WebSocketPeer.STATE_CLOSED means the connection has fully closed.
  33. # It is now safe to stop polling.
  34. elif state == WebSocketPeer.STATE_CLOSED:
  35. # The code will be -1 if the disconnection was not properly notified by the remote peer.
  36. var code = socket.get_close_code()
  37. print("WebSocket closed with code: %d. Clean: %s" % [code, code != -1])
  38. set_process(false) # Stop processing.

This will print something similar to:

  1. Got data from server: Request served by 7811941c69e658
  2. Got data from server: Test packet

最小服务器示例

这个例子将告诉你如何创建一个监听远程连接的WebSocket服务器,以及如何发送和接收数据。

  1. extends Node
  2. # The port we will listen to
  3. const PORT = 9080
  4. # Our WebSocketServer instance
  5. var _server = WebSocketServer.new()
  6. func _ready():
  7. # Connect base signals to get notified of new client connections,
  8. # disconnections, and disconnect requests.
  9. _server.client_connected.connect(_connected)
  10. _server.client_disconnected.connect(_disconnected)
  11. _server.client_close_request.connect(_close_request)
  12. # This signal is emitted when not using the Multiplayer API every time a
  13. # full packet is received.
  14. # Alternatively, you could check get_peer(PEER_ID).get_available_packets()
  15. # in a loop for each connected peer.
  16. _server.data_received.connect(_on_data)
  17. # Start listening on the given port.
  18. var err = _server.listen(PORT)
  19. if err != OK:
  20. print("Unable to start server")
  21. set_process(false)
  22. func _connected(id, proto):
  23. # This is called when a new peer connects, "id" will be the assigned peer id,
  24. # "proto" will be the selected WebSocket sub-protocol (which is optional)
  25. print("Client %d connected with protocol: %s" % [id, proto])
  26. func _close_request(id, code, reason):
  27. # This is called when a client notifies that it wishes to close the connection,
  28. # providing a reason string and close code.
  29. print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
  30. func _disconnected(id, was_clean = false):
  31. # This is called when a client disconnects, "id" will be the one of the
  32. # disconnecting client, "was_clean" will tell you if the disconnection
  33. # was correctly notified by the remote peer before closing the socket.
  34. print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
  35. func _on_data(id):
  36. # Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
  37. # and not get_packet directly when not using the MultiplayerAPI.
  38. var pkt = _server.get_peer(id).get_packet()
  39. print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
  40. _server.get_peer(id).put_packet(pkt)
  41. func _process(delta):
  42. # Call this in _process or _physics_process.
  43. # Data transfer, and signals emission will only happen when calling this function.
  44. _server.poll()

这将打印(当客户端连接时)与此类似的东西:

  1. Client 1348090059 connected with protocol: selected-protocol
  2. Got data from client 1348090059: Test packet ... echoing

高级聊天演示

godot demo projects 下 networking/websocket_chat 和 networking/websocket_multiplayer 有一个更高级的聊天演示demo, 可以选择使用多人中级抽象和高级多人演示demo.