gameClient/assets/scripts/loginPanel.ts

64 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-06-29 15:30:43 +08:00
import { _decorator, Button, Component, EditBox, Label, Node } from 'cc'
import { WsClient } from './wsclient'
const { ccclass, property } = _decorator
@ccclass('loginPanel')
export class loginPanel extends Component {
@property(EditBox)
private usernameInput: EditBox = null // 用户名输入框
@property(Label)
private statusLable: Label = null // 状态提示标签
@property(Button)
private loginButton: Button = null // 登录按钮
// 组件初始化完成后调用
start() {
this.loginButton.node.on(
Button.EventType.CLICK,
this.onLoginButtonClick,
this
)
// 监听websocket消息事件
window.addEventListener('ws-message', this.onMessage.bind(this))
}
protected onDestroy(): void {
window.removeEventListener('ws-message', this.onMessage.bind(this))
}
// 登录按钮点击处理函数
private onLoginButtonClick() {
const username = this.usernameInput.string.trim()
if (!username) {
this.statusLable.string = '请输入用户名'
return
}
const ws = WsClient.Instance
ws.connect('ws://echo.websocket.org')
this.statusLable.string = '正在连接服务器...'
setTimeout(() => {
const loginMsg = {
type: 'login',
username: username,
}
ws.send(loginMsg)
}, 1000)
}
private onMessage(event: CustomEvent) {
try {
const message = JSON.parse(event.detail) // 解析消息内容
if (message.type === 'loginSuccess') {
this.statusLable.string = '登录成功'
this.node.active = false
} else if (message.type === 'loginError') {
this.statusLable.string = '登录失败:' + message.reason
}
} catch (error) {
console.log('收到非json消息:', event.detail)
}
}
update(deltaTime: number) {}
}