(原) Godot使用ENetMultiplayerPeer实现的简单聊天室

原创文章,请后转载,并注明出处。

确实是比较简单,创建服务器,加入服务器。连接后,每次都会获取名字和内容。

get_tree().set_multiplayer(SceneMultiplayer.new(),self.get_path()) 啥意思?不用也没啥区别。
peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER) 这个有效果吗?估计得人多才能有测试。
为什么要在发送信息时使用 msg_rpc.rpc(my_name.text,send_message.text) ? 执行远程客户端上的msg()函数,并附带上当前的姓名和消息内容。

extends Node2D

@onready var host_button = $HostButton
@onready var join_button = $JoinButton
@onready var send_button = $SendButton
@onready var my_name = $MyName
@onready var info = $ScrollContainer/Label
@onready var send_message = $SendMessage

const MAX_PLAYER =30

@export var address = "127.0.0.1"
@export var port = 9999

func _ready():
	host_button.pressed.connect(_on_host_button_pressed)
	join_button.pressed.connect(_on_join_button_pressed)
	send_button.pressed.connect(_on_send_button_pressed)

	multiplayer.peer_connected.connect(_on_peer_connected) 				        # 连接事件(服务端和客户端都调用)
	multiplayer.peer_disconnected.connect(_on_peer_disconnected)				# 断开连接事件。当一个节点断开连接时,该信号会在剩余的每个节点上发出
	multiplayer.connected_to_server.connect(_on_connected_to_server)			# 客户端连接到服务器
	multiplayer.connection_failed.connect(_on_connection_failed) 				# 客户端连接服务器失败
	multiplayer.server_disconnected.connect(_on_server_disconnect)				# 客户端被禁止连接


# 按钮:启动服务器
func _on_host_button_pressed():
	var peer = ENetMultiplayerPeer.new()
	var err = peer.create_server(port, MAX_PLAYER)
	if err != OK:
		info.text += "\n" + err
		return
	info.text += "\nA.启动服务器"
	peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER)
	#get_tree().set_multiplayer(SceneMultiplayer.new(),self.get_path())
	multiplayer.set_multiplayer_peer(peer)	
	info.text += "\nB.等待玩家加入..."
	
# 按钮:加入服务器
func _on_join_button_pressed():
	var peer = ENetMultiplayerPeer.new()
	var err = peer.create_client(address,port)
	if err != OK:
		info.text += "\n" + err
		return
	peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER)
	#get_tree().set_multiplayer(SceneMultiplayer.new(),self.get_path())
	multiplayer.set_multiplayer_peer(peer)	
	info.text += "\na.玩家加入"

# 按钮:发送信息事件
func _on_send_button_pressed():
	msg_rpc.rpc(my_name.text,send_message.text)

# 连接事件(服务端和客户端都调用)
func _on_peer_connected(id):
	info.text += "\n" + str(multiplayer.get_unique_id()) +":玩家连接 " + str(id)
	
func _on_peer_disconnected(id):
	info.text += "\n" + str(multiplayer.get_unique_id()) +":玩家断开连接 " + str(id)
	
# 客户端连接到服务器
func _on_connected_to_server():
	info.text += "\nb." + str(multiplayer.get_unique_id()) + "连接到服务器"
	
func _on_connection_failed():
	info.text += "\n连接服务器失败"

func _on_server_disconnect():
	info.text += "\n服务器禁止连接"

@rpc("any_peer","call_local")
func msg_rpc(user,data):
	info.text += "\n" + str(user) + ": " + str(data)

相关文章