1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import { Server, Client, Packet, Authorizer } from 'mosca'
const setting = { port: 12345, http: { port: 12346, bundle: true, } }
const server = new Server(setting) const auth = new Authorizer()
server.on('clientConnected', (client: Client) => { console.log('客户端连接的ID:', client.id) })
server.on('clientDisconnecting', (client: Client) => { console.log('客户端正在断连', client.id) })
server.on('clientDisconnected', (client: Client) => { console.log('客户端已经断连', client.id) })
server.on('published', (packet: Packet, client: Client) => { console.log('发布消息:', packet) })
server.on('subscribed', (topic, client: Client) => { console.log('订阅主题:', topic) })
server.on('unsubscribed', (topic, client: Client) => { console.log('取消订阅:', topic) })
server.on('ready', () => { console.log('服务器启动成功!')
server.authenticate = (client: Client, username: string, password: string, callback) => { if (username == 'limo' && password == 'limo123') { return callback(null, true) } else { return callback(null, false) } }
server.authorizePublish = (client: Client, topic: string, payload: string, callback) => { return callback(null, true) }
server.authorizeSubscribe = (client: Client, topic: string, callback) => { return callback(null, true) } });
|