Advanced Chat
Here, we have a slightly more complex chat, with both chat and emote messages. By using type routing, we can listen for each message type separately. We've also shown how to add TypeScript to your connection and messages.
Finally, we're tracking the active users through a simple greet event. When a new user joins, all existing users greet the new user, allowing them to compile a list of all connected users.
In this window, you are .... To chat with yourself, open this page in another tab.
no messages yet...
Connected Users
import { connect } from 'itty-sockets'
type ChatMessage = { type: 'chat', text: string }
type EmoteMessage = { type: 'emote', action: string }
const chat = connect('examples:typed-chat', {
announce: true, // include uid/alias in join/leave events
echo: true, // receive your own messages back
as: '...',
})
.on('join', ({ uid, alias, users }) => {
// 1. add user to list of connected users
// 2. privately greet the new user
})
.on('leave', ({ uid, alias, users }) => {
// remove user from list of connected users
})
// type routing — each type gets its own handler
.on<ChatMessage>('chat', ({ alias, text }) => {
// add message to chat log: "Kevin: hello!"
})
.on<EmoteMessage>('emote', ({ alias, action }) => {
// add emote to chat log: "*Kevin waves*"
})
.on<GreetingMessage>('greeting', ({ uid, alias }) => {
// add user to list of connected users
})
chat.send<ChatMessage>({ type: 'chat', text: 'hello!' })
chat.send<EmoteMessage>({ type: 'emote', action: 'waves' })Alternatively, you can use an event map to type the connection while keeping your downstream code cleaner:
import { connect } from 'itty-sockets'
type ChatMessage = { type: 'chat', text: string }
type EmoteMessage = { type: 'emote', action: string }
type Events = {
chat: ChatMessage
emote: EmoteMessage
}
const chat = connect<Events>('examples:typed-chat', {
announce: true, // include uid/alias in join/leave events
echo: true, // receive your own messages back
as: '...',
})
.on('join', ({ uid, alias, users }) => {
// 1. add user to list of connected users
// 2. privately greet the new user
})
.on('leave', ({ uid, alias, users }) => {
// remove user from list of connected users
})
// type routing — each type gets its own handler
.on<ChatMessage>('chat', ({ alias, text }) => {
// add message to chat log: "Kevin: hello!"
})
.on<EmoteMessage>('emote', ({ alias, action }) => {
// add emote to chat log: "*Kevin waves*"
})
.on<GreetingMessage>('greeting', ({ uid, alias }) => {
// add user to list of connected users
})
chat.send({ type: 'chat', text: 'hello!' })
chat.send({ type: 'emote', action: 'waves' })