56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
|
import { _decorator, Button, Component, EditBox, Label } from 'cc'
|
||
|
import { WsClient } from './wsclient'
|
||
|
const { ccclass, property } = _decorator
|
||
|
|
||
|
@ccclass('gamePanel')
|
||
|
export class gamePanel extends Component {
|
||
|
@property(EditBox)
|
||
|
private messageInput: EditBox = null
|
||
|
@property(Label)
|
||
|
private messageLabel: Label = null
|
||
|
@property(Button)
|
||
|
private sendButton: Button = null
|
||
|
|
||
|
private onSendButtonClick() {
|
||
|
const msg = this.messageInput.string.trim()
|
||
|
if (!msg) return
|
||
|
const ws = WsClient.Instance
|
||
|
const chatMsg = {
|
||
|
type: 'chat',
|
||
|
content: msg,
|
||
|
}
|
||
|
ws.send(chatMsg)
|
||
|
this.messageInput.string = ''
|
||
|
this.appendMsg('你:' + msg)
|
||
|
}
|
||
|
|
||
|
private onMessage(event: CustomEvent) {
|
||
|
try {
|
||
|
const msg = JSON.parse(event.detail)
|
||
|
if (msg.type === 'chat') {
|
||
|
this.appendMsg(`${msg.sender}:${msg.content}`)
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.log('收到非json消息:', event.detail)
|
||
|
}
|
||
|
}
|
||
|
private appendMsg(msg: string) {
|
||
|
this.messageLabel.string += msg + '\n'
|
||
|
}
|
||
|
|
||
|
start() {
|
||
|
this.sendButton.node.on(
|
||
|
Button.EventType.CLICK,
|
||
|
this.onSendButtonClick,
|
||
|
this
|
||
|
)
|
||
|
window.addEventListener(`ws-message`, this.onMessage.bind(this))
|
||
|
}
|
||
|
|
||
|
protected onDestroy(): void {
|
||
|
window.removeEventListener(`ws-message`, this.onMessage.bind(this))
|
||
|
}
|
||
|
|
||
|
update(deltaTime: number) {}
|
||
|
}
|