服务端 server.gd
extends Node
const PORT = 9080
var tcp_server := TCPServer.new()
var socket := WebSocketPeer.new()
# 输出信息到富文本框
func log_message(message):
var time = "[color=#aaaaaa] %s [/color]" % Time.get_time_string_from_system()
%TextServer.text += time + message + "\n"
# 服务器监听
func _ready():
if tcp_server.listen(PORT) != OK:
log_message("Unable to start server.")
set_process(false) # 监听不成功时停止刷新
func _process(_delta):
while tcp_server.is_connection_available(): # 有可用连接时
var conn: StreamPeerTCP = tcp_server.take_connection()
assert(conn != null)
socket.accept_stream(conn)
socket.poll()
if socket.get_ready_state() == WebSocketPeer.STATE_OPEN: # 接收信息
while socket.get_available_packet_count():
log_message(socket.get_packet().get_string_from_utf8())
func _exit_tree():
socket.close()
tcp_server.stop()
# 按发送键
func _on_button_pong_pressed():
socket.send_text("打")
客户端 client.gd
extends Node
var websocket_url = "ws://localhost:9080"
var socket := WebSocketPeer.new()
func log_message(message):
var time = "[color=#aaaaaa] %s [/color]" % Time.get_time_string_from_system()
%TextClient.text += time + message + "\n"
func _ready():
if socket.connect_to_url(websocket_url) != OK:
log_message("Unable to connect.")
set_process(false)
func _process(_delta):
socket.poll()
if socket.get_ready_state() == WebSocketPeer.STATE_OPEN: # 接收信息
while socket.get_available_packet_count():
log_message(socket.get_packet().get_string_from_utf8())
func _exit_tree():
socket.close()
# 发送按键
func _on_button_ping_pressed():
socket.send_text("打它")